Reputation: 14379
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?
Upvotes: 4
Views: 1448
Reputation: 163228
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.
Upvotes: 17
Reputation: 26060
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) );
Upvotes: 3
Reputation: 96937
Dereference str
:
print ("%s", *str); /* assuming *str is null-terminated */
Upvotes: 5