tags:

views:

102

answers:

1

Hi..

I can't seem to understand the difference between the different declarations on an array or a 2d array.
for instance:

void swap(char **a, char **b) {
    char *t = *a;
    *a = *b;
    *b = t;
}
int main(int argc, char **argv) {
    char a[] = "asher";
    char b[] = "saban";
    swap(&a,&b);
}

this code doesn't compile, it outputs:

warning: passing argument 1 of ‘swap’ from incompatible pointer type
test.c:10: note: expected ‘char **’ but argument is of type ‘char (*)[6]’

isn't a a pointer to first cell of char array and &a is a pointer to pointer?

another example is:

char (*c)[3];  
char (*d)[3];  
swap(c,d);

doesn't compile either.. is char (*c)[3] same as a pointer to char a[] = "ab" ?

However this does compile:

char *c[3];
char *d[3];
swap(c,d);

so i'm totally confused. Why is there a difference? Is there some rules about that issue to prevent me from mistaking all the time?

Thank you all

+7  A: 

I think that this is the source of your confusion.

An array variable is a fixed object. It refers to a fixed set of array members. It cannot be changed, although the values of the array members can.

In all expression contexts other than as the argument to unary & (address of) and sizeof an array will decay into a pointer to its first element.

Given:

char a[] = "asher";

The expression a will decay to a pointer to char (char*) and will point to the first character of a.

The expression &a is a pointer to an array of char (char (*)[]). It is a pointer to the complete array rather that a pointer to the first character. It is a different type to a pointer to the first character of the array although it will have the same value as a pointer to the first character of the array.

However, neither of the expressions a and &a are lvalues, they are temporary pointer values.

You cannot swap arrays, you can only swap pointers but to do this you need lvalue pointers whose address you can take.

void swap(char **a, char **b);

int main(int argc, char **argv) {
    char a[] = "asher";
    char b[] = "saban";
    char* pa = a;
    char* pb = b;
    swap(&pa, &pb);
}
Charles Bailey
Thank you very much, that's a very informative answer
rob