简体   繁体   中英

How to get char* from char**

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?

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.

取消引用str

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

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) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM