繁体   English   中英

将指向char数组的指针传递给函数

[英]Passing pointer to char array to function

我在尝试将字符数组的地址传递给函数时遇到了一个小问题,这是我尝试做的一个简单示例:

char a[20] = {"hello"};
printit( &a );

你能给我他printit函数的声明(也许是为什么),我期待这样的事情:

void printit( char ** value );
or void printit( char * value[] );

工作,但事实并非如此。

*错误消息:

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 *[]'

提前致谢。

问候,最大。

您的参数&a是指向20个字符的数组的指针,因此:

void printit(char (*value)[20]);  // value is a pointer to an array of 20 chars

但是,更常见的是(尤其是使用字符串)将调用更改为

printit(a);   // a will be passed as pointer to first elelemt, i.e. 'a' can be used as pointer to char

并将printit定义为

void printit(char *value)
{
     printf("The string is: %s", value);
}

*编辑..出错

您不是在声明char *数组,而是在声明char数组。 在变量声明中添加星号并删除&可以使其工作:

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.

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