4

I understand that & is used to reference the address of object so &char* = char**. Is there anyway to reverse this so that I can get char* from char**?

So I have:

char** str; //assigned to and memory allocated somewhere printf ("%s", str); //here I want to print the string. 

How would I go about doing this?

3 Answers 3

17

You can use the dereference operator.

The dereference operator operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer.

char** str; //assigned to and memory allocated somewhere printf ("%s", *str); //here I want to print the string. 
Sign up to request clarification or add additional context in comments.

Comments

5

Dereference str:

print ("%s", *str); /* assuming *str is null-terminated */ 

Comments

3

If you have a T* (called a pointer to an object of type T) and want to get a T (an object of type T), you can use the operator *. It returns the object pointed by your pointer.

In this case you've got a pointer to an object of type char* (that's it: (char*)*) so you can use *.

Another way could be that of using operator [], the one you use to access the arrays. *s is equal to s[0], while s[n] equals *(s+n).

If your char** s is an array of char*, by using printf( "%s", *str ) you'll print the first one only. In this case it's probably easier to read if you use []:

for( i = 0; i < N; ++ i ) print( "%s\n", str[i] ); 

Althought it's semantically equivalent to:

 for( i = 0; i < N; ++ i ) print( "%s\n", *(str+i) ); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.