2

Possible Duplicate:
Passing multidimensional arrays as function arguments in C

I'm trying to use general swap function:

void swap(void **p, void **q){
    void *tmp;
    tmp=*p;
    *p=*q;
    *q=tmp;
}


int main(){
    int M=5;
    int N=6;
    char*w[M][N];

    swap(&w[1][2], &w[2][2]);

    return 0;
    }

Let's assume that w is initialized already with values, I am wondering only about the way I should send the arguments

I'm trying to figure out how should I send the arguments to swap in this case.

Let's assume that N=M=2; so I have w looks like {{"stack", "overflow"},{"best", "site"}}

  1. swap(w[i][j],w[k][r]) is not the correct option since w[i][j] is reference to an actual string and swap gets **void, where only w[i][j] is a pointer to only *char, so
  2. swap(&w[i][j], &w[k][r]) looks like the right options. since it's a pointer to char*, but I get passing arguments of swap from incompatible pointer type, How come?
Community
  • 1
  • 1
Jozef
  • 193
  • 1
  • 9

3 Answers3

3

You can convert char * to void * (think if it as a special case), but you cannot convert char ** to void ** and do anything meaningful with the result.

For the same reason, you can convert int to short, but you cannot convert int * to short * and expect the compiler not to complain.

(It happens to work on common architectures, but nothing in the C standard guarantees that two different pointer types have the same representation, with a couple exceptions.)

void swap(char **p, char **q)
{
    char *tmp;
    tmp = *p;
    *p = *q;
    *q = tmp;
}
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
2

You have to cast void** to char*, or char* to void** depending on how you want the code to be written.

I don't think C supports any generic-ish way of having a function blind to the type of data it's working with.

The typical way of writing a swap function would be for each data type you expect to use it with so you would end up writing separate methods for swapping int*, char*, ect instead of using void pointers.

John Lotacs
  • 1,184
  • 4
  • 20
  • 34
1

Your swap function expects void** as arguments, but you pass char**s. That's what the compiler complains about. While all object-pointer types can be implicitly converted to void*, that is not true for void**, hence you have to cast the arguments,

swap((void**)&w[1][2], (void**)&w[2][2]);
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431