我有一个关于将 c 中的数组传递给函数的问题。
当我运行这个程序时,它给我一个段错误
int main()
{
char **ptr= NULL;
test(ptr);
printf("%s", ptr[0]);
return 0;
}
void test(char **ptr)
{
ptr = (char **) malloc(sizeof(char *));
ptr[0] = (char *) malloc(sizeof(char)*5);
strcpy(ptr[0], "abc");
return;
}
但这很好用
int main()
{
char **ptr= NULL;
test(&ptr);
printf("%s", ptr[0]);
return 0;
}
void test(char ***ptr)
{
*ptr = (char **) malloc(sizeof(char *));
*ptr[0] = (char *) malloc(sizeof(char)*5);
strcpy(*ptr[0], "abc");
return;
}
谁能解释一下为什么?
最佳答案
您正在传递参数 ptr
按值;形参 ptr
在test
是一个与实际参数不同的对象 ptr
在main
, 所以改变 test::ptr
的值未反射(reflect)在 main::ptr
中.
因此,您需要传递一个指针给ptr
进入test
, 和 test
需要取消引用该指针以写入正确的对象。
对于任何类型 T
,如果要修改函数参数的值,需要进行如下操作:
void foo( T *param )
{
*param = ...;
}
void bar( )
{
T obj;
foo( &obj );
}
在此特定实例中,T
是char **
.
关于c - 在c中传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18387797/