[英]Passing pointer to char array to function
i had a little problem trying to pass the address for a character array to a function, here is a simple example of what i am trying to do : 我在尝试将字符数组的地址传递给函数时遇到了一个小问题,这是我尝试做的一个简单示例:
char a[20] = {"hello"};
printit( &a );
can you please give me the declaration of he printit function ( and maybe why ), i was expecting something like : 你能给我他printit函数的声明(也许是为什么),我期待这样的事情:
void printit( char ** value );
or void printit( char * value[] );
to work, but it is not. 工作,但事实并非如此。
*Error messages : *错误消息:
void printit( char ** value ); => cannot convert parameter 1 from 'char (*)[20]' to 'char **'
void printit( char * value[] ); => cannot convert parameter 1 from 'char (*)[20]' to 'char *[]'
thanks in advance. 提前致谢。
Regards, max. 问候,最大。
Your parameter &a
is a pointer to an array of 20 chars, hence: 您的参数
&a
是指向20个字符的数组的指针,因此:
void printit(char (*value)[20]); // value is a pointer to an array of 20 chars
. 。
However, more commonly (especially with strings) would be to change the call into 但是,更常见的是(尤其是使用字符串)将调用更改为
printit(a); // a will be passed as pointer to first elelemt, i.e. 'a' can be used as pointer to char
and define printit as 并将printit定义为
void printit(char *value)
{
printf("The string is: %s", value);
}
*Edited .. made a mistake *编辑..出错
You are not declaring an array of char* you are declaring an array of char. 您不是在声明char *数组,而是在声明char数组。 Adding asterisk to your variable declaration and removing the & should make it work:
在变量声明中添加星号并删除&可以使其工作:
void printit(char** arr){
string tmp(arr[0]);
cout<<tmp<<endl;
}
char* a[20] = {"hello"};
printit( a );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.