c - How exactly pointer to an array works? -
can explain how these values printed , why p , *p returning same values.
#include <stdio.h> int main(){ int arr[] = {1,2,3,4}; int (*p)[4]; p = &arr; printf("%u %u %u %u %u", arr, &p, p, *p, **p); p++; printf("\n%u %u %u %u %u", arr, &p, p, *p, **p); return 0; }
outputs on machine follows:
2686768 2686764 2686768 2686768 1 2686768 2686764 2686784 2686784 2686792
your example messy, pointer arithmetic messy in general, disrespectful types. example not make sense type theory point of view.
arr
points first element of array. note arr[i]
equivalent *(arr+i)
. arr
4-elements array of type int
.
p
pointer 4-element array of type int
.
you assign p
address of &arr
, has same address arr
(but type different, see below).
then print out , means:
arr
address of first element of array&p
address ofp
p
address of&arr
(whole array), address ofarr
, address of first element in array*p
address ofarr
, address of first element in array**p
trying dereference*p
, dereferencingarr
, first element of array
after increment p++
: arr
, &p
don't change, rest does
from c book
we have emphasized in cases, name of array converted address of first element; 1 notable exception being when operand of sizeof, essential if stuff malloc work. case when array name operand of & address-of operator. here, converted address of whole array. what's difference? if think addresses in way ‘the same’, critical difference have different types. array of n elements of type t, address of first element has type ‘pointer t’; address of whole array has type ‘pointer array of n elements of type t’; different. here's example of it:
int ar[10]; int *ip; int (*ar10i)[10]; /* pointer array of 10 ints */ ip = ar; /* address of first element */ ip = &ar[0]; /* address of first element */ ar10i = &ar; /* address of whole array */
Comments
Post a Comment