user1762571
user1762571

Reputation: 1949

Two dimensional array and pointers in c

int s[4][2]={1,2,3,4,5,6,7,8};
printf("\n%u,%d",s+1,*(s+1));

Ans 2665496,2665496

In two dimensional array (s+1) gives the address of second row but why *(s+1) is not giving the value 3?

Upvotes: 1

Views: 342

Answers (4)

newacct
newacct

Reputation: 122519

s has type int [4][2], i.e. it is an array of arrays.

Used in most expressions, it is implicitly converted to a pointer to its first argument, having type int (*)[2], i.e. pointer to array. So s+1 has type int (*)[2], pointer to array. This is the pointer to the second row (not an int, but an entire row).

*(s+1) is the dereference of that pointer to array. Hence, it has type int [2], i.e. an array of ints.

As with s above, by using it (an array) in most contexts (in this case as an argument to printf), it gets implicitly converted to a pointer to its first element, i.e. type int * a pointer to int. This is a pointer to the int that has value 3.

Since you are printing them pretending that they are integers, and both of them are pointers, they will both print addresses. The addresses will be the same, since the address of an array is the same as the address of its first element, even though the types of the pointers passed in were different.

You are kind of abusing the type system and passing in pointers of various types that are not compatible with the type you told printf. The reason this works is because C varargs are not type-checked.

Upvotes: 1

aymericbeaumet
aymericbeaumet

Reputation: 7342

Note that your array initialization results in a warning under gcc (got version 4.2.1):

main.c:3: warning: missing braces around initializer
main.c:3: warning: (near initialization for ‘s[0]’)

If you want to create an array of 2 rows / 4 columns, you've to do it this way:

int s[2][4] = {{1,2,3,4}, {5,6,7,8}};

You could then use printf as:

printf("%p,%d\n", s+1, **(s+1));

Upvotes: 0

Crowman
Crowman

Reputation: 25936

Because s is effectively a pointer to a pointer, so if you dereference it, you get a pointer, not an int.

Upvotes: -1

Jens Gustedt
Jens Gustedt

Reputation: 78973

As you say correctly s+1 is the address of the second row. So *(s+1) or more readable s[1] is a row, not a number. So it can't have "value 3".

Upvotes: 6

Related Questions