i was practicing pointers and i saw that when i define a pointer and assign an array to that pointer, i was able to get the value in a specific index when i use the pointer name with that index instead of array name, like,
int arr[5] = {1,2,3,4,5};
int *ptr;
ptr = arr;
printf("%d", ptr[1]); // prints out 2
I was expecting to see the value when i use *ptr[1] and the specific index adress when i use ptr[1], but when i use *ptr[1] i get compiler error. I thought pointer name keeps the adress and using the name with * gives the value in that adress.
Am i missing something here? Why pointer with array works that way?
The misunderstanding here is that pointers and arrays have similar behaviours in C, as in you can treat a pointer like an array, and an array like a pointer.
In effect x[n]
is the same as *(x + n)
and vice-versa. x[0]
is just *x
.
As such, ptr[1]
will return a de-referenced int*
or in other words an int
.
If you want the actual address you need to do either ptr + n
or &ptr[n]
, both of which are equivalent, they're int*
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.