1

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?

3
  • Yes, strings + 2 is &(strings[2]). No, the lengths of the strings will not always differ. Commented Apr 5, 2014 at 10:21
  • char** strings is not an array of pointers, sry. Commented Apr 5, 2014 at 11:47
  • To be clear, strings[2] is a pointer to the first character of the third string. Commented Apr 5, 2014 at 13:02

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.