Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 435
beemavishnu Avatar asked Oct 29 '12 10:10

beemavishnu


1 Answers

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

like image 88
ecatmur Avatar answered Oct 18 '22 19:10

ecatmur