Reputation: 558
Well I don't work a lot with a pointers but now I get confused. I'm trying create array of pointers at strings (in this example just 2 pointers).
char str[120];
char* st[2];
int i=1;
while (fgets(str,120,f)) {
printf("%s",str);
st[i]=&str;
i++;
if (i==3)
break;
}
for (i=1;i<=2;i++) {
puts(st[i]);
}
warning: assignment from incompatible pointer type [enabled by default]
so can you help me understand all this situation with pointers on a strings. Please
Upvotes: 0
Views: 79
Reputation: 111
Arrays always use 0-based index.
for example:
int my_arr[] = { 10, 11, 12, 13, 14, 15 };
means that the array my_arr has 6 elements starting from index 0 till 6-1 (5). So, an N element array will have its indices from 0 to N-1. Also, note that my_arr by itself is also a pointer to the array.
define a int pointer:
int *iPtr = my_arr; // note that we do not use &my_arr here. my_arr is already a pointer to the array it defined.
or
int *iPtr;
iPtr= my_arr;
they are the same.
In the figure, the box represent the values and their addresses are written besides the boxes.
When you iterate over the array using variable i
as index. You basically do the following indirectly:
i = 0
my_arr[i]
is same as
my_arr[0]
is same as
*(my_arr + 0)
is same as (substitute the value of box named my_arr)
*(20014000+0)
The * operator gets you the value at the address 0x20014000
in this example which is 10
.
The above operation is also same as
iPtr[0] or *(iPtr+0)
Look at the box named iPtr
, it also contains the same value 0x20014000
.
Now lets define an array of pointers:
int *myptr_arr[3];
int varA = 25;
int varB = 34;
int varC = 67;
myptr_arr[0] = &varA; // note that varA is not a pointer, to get its address use &
myptr_arr[1] = &varB; // note that varB is not a pointer, to get its address use &
myptr_arr[2] = &varC; // note that varC is not a pointer, to get its address use &
once again, when you write myptr_arr[0]
it translates to
*(myptr_arr + 0)
*(20152000 + 0)
which will get you 0x20162000
i.e. the value of box named [0]
= the address of varA
. Now to get the value at this address, you need to dereference it with *
operator.
*myptr_arr[0]
which is same as * ( *(myptr_arr + 0) )
which is same as *(0x20162000)
which is the value of box varA
Please see : Example usage of pointers
Upvotes: 2