I have a basic doubt in 2D arrays (C Language). Consider a declaration of a 2D array as follows
int array[3][5];
Now when I do the following, the output of both th below printf’s is the same:
printf("%u\n", array);
printf("%u\n", *(array));
Now when try to to the following:
printf("%u\n", array+1);
printf("%u\n", *(array)+1);
The outputs are different. I get that the 2nd printf refers to array[0][1] and the first one to array[1][0]. How does this work? array is a pointer to what?
Thanks in advance
Arrays are not pointers. Ignore any answer, book, or tutorial that tries to tell you otherwise.
An expression of array type, in most contexts, is converted (at compile time) into a pointer to the array’s first element. The exceptions are:
sizeof(sizeof arryields the size of the array, not the size of a pointer)&(&arryields the address of the array, not of its first element — same memory location, different type). This is particularly relevant to your example.char s[6] = "hello";doesn’t copy the address of the string literal, it copies its value)A 2-dimensional array is nothing more or less than an array of arrays. There are other data structures that can be used with the same
x[y][z]syntax, but they’re not true 2-dimensional arrays. Yours is.The
[]indexing operator is defined in terms of pointer arithmetic.x[y]means*(x+y).The behavior of your code follows from these rules.
Read section 6 of the comp.lang.c FAQ. It’s the best explanation of this stuff I’ve seen.
And don’t use
"%u"to print pointer values; convert tovoid*and use"%p".