8

Below is an example of two dimensional array.

int s[5][2] = { {0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9} }; int (*p)[2]; 

If I write p = &s[0]; there is no error. But if I write p = s[0]; there is an error, even though &s[0] and s[0] will give the same address.

Please let me know why there is a differnece, even though both give the same address.

2
  • To make the question complete, it would be better to post the error message you received. Commented Oct 29, 2012 at 10:41
  • С is a typed language, which means that it strictly controls types of the values being assigned. Just because two addresses are the same does not mean that they are compatible by type. Commented Jun 17, 2018 at 21:43

3 Answers 3

17

The addresses are the same, but the types are different.

&s[0] is of type int (*)[2], but s[0] is of type int [2], decaying to int *.

The result is that when performing arithmetic on p, the pattern with which it walks over the array will depend on its type. If you write p = &s[0] and then access p[3][1], you are accessing s[3][1]. If on the other hand you write int *q = s[0], you can only use q to access the first subarray of s e.g. q[1] will access s[0][1].

Sign up to request clarification or add additional context in comments.

Comments

0

Close, but not quite. s is a pointer to the first element of the array. It's also the alias for that array - the compiler knows that it points to a specific number of elements.

So, &s[0] returns the address of the first element while s[0] returns the element itself.

*p however is just a pointer to an int. It may be more elements than that, but the compiler sure doesn't know.

2 Comments

Oh yeah, course. Oops! p is an array of points to an int, right? Gawd, has it been that long since I used a strongly typed language daily. :laughs as he imagines what would happen if he were doing COM work right now boom, computer splode?:
The type of *p is an array 2 of int. When evaluated, the array *p is converted to a pointer to int.
-2

gcc would display a warning as you are trying to assign a data type (int *) to different data type (int **). Not sure of other compilers.

1 Comment

It doesn't really matter. C does not differentiate between "warnings" and "errors".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.