I'm back with this example again with a question.
#include <stdio.h>
int main()
{
char* arr[3] = { "geek", "Geeks", "Geeksfor" };
for (int i = 0; i < 3; i++) {
printf("*(arr+%d) : %p\n", i, *(arr+i));
}
printf("\n");
for (int i = 0; i < 3; i++) {
printf(" arr+%d : %p\n", i, arr+i);
}
printf("\n");
for (int i = 0; i < 3; i++) {
printf(" &arr+%d : %p\n", i, &arr+i);
}
printf("\n");
return 0;
}
And I had this answer:
printf("Indeks : %d, Address of (arr) : %p\n",i , *(arr+i));
printf("Indeks : %d, Address of (&arr) : %p\n",i , arr+i);
printf("Indeks : %d, Address of (&arr) : %p\n",i , &arr+i);
The tag
arr + i
is the address of the pointer at location
i
in the array
arr
. So pointer 0, 1 and 2 (3 items).
- You take the content of
arr + i
, which is a pointer which points to a string of characters and will be allocated by the compiler. Its actual value has nothing to do with pointer arithmetic, it is purely a random address as allocated by the compiler.
- You take the actual pointer at
arr + i
and print its address. And since it is one of three pointers, they will each be 8 bytes distant from their predecessor.
- You are printing the address of the array itself, plus 0, 1 and 2. And since the array is 3 pointers in size, this address will increase by the size of the array itself.
But why does it shift 3*8 bytes ?
Doesn't it work like that each element of array has a specific address like here? :
https://i.postimg.cc/k5Zv8mpk/obraz-2023-10-18-210634239.png[
^] in my case &arr+i shows only the sum of 3 arrays which is 3*8 bytes why ?
What if I used
**ptr
? Like here
char**ptr = &arr
??? If I type
ptr + 1
, it shifts also by 24 bytes? How does he know that he must shift by 24 bytes or rather how does he know he has to go through 3 elements of arrays?
Example with:
If I had a normal array like
val[2]
, then typing
val+1
will shift it by 4 bytes. What is the arithmetic behind that &arr is 3bytes*sizeof(char**) ? And the other one that usually is 8 bytes or 4 bytes. Because I believed that &arr + 1 is an address of
arr + 1
and &
arr + 0
is an address of
arr + 0
. So what is the address of
arr + 1
?
What I have tried:
I tried understanding it from many websites ;>