Reputation: 129
Let's say I have an array of pointers in C. For instance:
char** strings
Each pointers in the array points to a string of a different length.
If I will do, for example: strings + 2
, will I get to the third string, although the lengths may differ?
Upvotes: 1
Views: 132
Reputation: 2183
i think you are looking to access third element through expression
strings[2];
but this will not be the case because look at the type of expression string[2]
Type is char *
As according to the standards
A 'n' element array of type 't' will be decayed into pointer of type __t__.With the exception when expression is an operand to '&' operator and 'sizeof' operator.
so strings[2] is equivalent to *(strings + 2) so it will print the contents of the pointer to pointer
at third location,which is the contents of a pointer
i.e an address.
But
strings+2;
whose type is char **
will print the 3 rd location's address,i.e,address of the 3rd element of array of pointer, whose base address is stored in **string.
But in your question you have not shown any assignment to the char ** strings
and i am answering by assuming it to be initialised with particular array of pointers.
According to your question it is silly to do
*(strings + 2)
As it is not initialised.
Upvotes: 0
Reputation: 9642
Yes, you will (assuming that the array has been filled correctly). Imagine the double pointer situation as a table. You then have the following, where each string is at a completely different memory address. Please note that all addresses have been made up, and probably won't be real in any system.
strings[0] = 0x1000000
strings[1] = 0xF0;
...
strings[n] = 0x5607;
0x1000000 -> "Hello"
0xF0 -> "World"
Note here that none of the actual text is stored in the strings. The storage at those addresses will contain the actual text though.
For this reason, strings + 2
will add two to the strings pointer, which will yield strings[2]
, which will yield a memory address, which can then be used to access the string.
Upvotes: 4
Reputation: 9680
strings + 2
is the address of the 3rd element of the buffer pointed to by string
.
*(strings + 2)
or strings[2]
is the 3rd element which is again a pointer to a buffer of characters.
Upvotes: 2