Re: array pointer

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]


>> int  *s_ptr;
>> int  **d_ptr;
>> int arr[2][2]={1,2,3,4};
>
> One image is worth a thousand words, so here it goes:
>
> arr is something like this in memory:
>
> +---+---+---+---+
> | 1 | 2 | 3 | 4 |
> +---+---+---+---+
>
> d_ptr would require something like:
>
> +---------+---------+
> | pointer | pointer |
> +----|----+----|----+
>     |         |     +---+---+
>     |         +---> | 3 | 4 |
>     |     +---+---+ +---+---+
>     +---> | 1 | 2 |
>           +---+---+
>
> Ie. in arr all the numbers are lied linearly in memory whereas
> int **d_ptr is an array of pointers to array of ints.

I would say int **d_ptr is really a pointer to a pointer and not
necessarily an array of pointers.

So, the following is fine:
d_ptr = &s_ptr;
printf("s_ptr: %d, d_ptr: %d\n", *s_ptr, **d_ptr);

and displays "s_ptr: 1, d_ptr: 1"

To (attempt to) answer your original question though, the problem is
that "arr" will give you the address of the array, not the address of
a pointer to the array. For each extra dimension of the array you need
to add a * when referring to the name of the array without indices in
order to de-reference the additional dimensions.

So,
1-dimensional array
int *s_ptr;
int arr[2]={1,2};
s_ptr = arr; /* Ok because arr references the address of the array
immediately */

2-dimensional array
int *s_ptr;
in arr[2][2]={1,2,3,4};
s_ptr = *arr; /* Ok because the * de-references arr to the address of
the array, but arr is not the address of a pointer to the array */

3-dimensional array
int *s_ptr;
int arr[2][2][2]={1,2,3,4,5,6,7,8};
s_ptr = **arr; /* Ok, again each * de-references additional dimensions
of the array */

But these references are not pointers, which is why int **d_ptr; int
arr[2][2]={1,2,3,4}; d_ptr = arr; will not work, arr will not be a
pointer to a pointer.

HTH,
David McMurray.
--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html


[Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

Add to Google Powered by Linux