[英]How to get char* from char**
I understand that & is used to reference the address of object so &char* = char**
. 我明白&用于引用对象的地址,所以
&char* = char**
。 Is there anyway to reverse this so that I can get char*
from char**
? 有没有反过来这样我可以从
char**
获得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. 解引用运算符对指针变量进行操作,并返回与指针地址处的值等效的l值。 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 *
. 如果你有一个
T*
(称为指向T
类型对象的指针)并且想要得到一个T
(一个T
类型的对象),你可以使用运算符*
。 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 *
. 在这种情况下,你有一个指向
char*
类型对象的指针(就是它: (char*)*
)所以你可以使用*
。
Another way could be that of using operator []
, the one you use to access the arrays. 另一种方法可能是使用operator
[]
,即用于访问数组的那个。 *s
is equal to s[0]
, while s[n]
equals *(s+n)
. *s
等于s[0]
,而s[n]
等于*(s+n)
。
If your char** s
is an array of char*
, by using printf( "%s", *str )
you'll print the first one only. 如果你的
char** s
是一个char*
数组,通过使用printf( "%s", *str )
你只打印第一个。 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) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.