beemavishnu
beemavishnu

Reputation: 105

Address of pointer to an array

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.

Upvotes: 8

Views: 229

Answers (3)

Sakthi Kumar
Sakthi Kumar

Reputation: 3045

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.

Upvotes: -2

enhzflep
enhzflep

Reputation: 13089

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.

Upvotes: 0

ecatmur
ecatmur

Reputation: 157354

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].

Upvotes: 17

Related Questions