c - 在c中传递数组

标签 c arrays pointers segmentation-fault

我有一个关于将 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 按值;形参 ptrtest是一个与实际参数不同的对象 ptrmain , 所以改变 test::ptr 的值未反射(reflect)在 main::ptr 中.

因此,您需要传递一个指针ptr进入test , 和 test需要取消引用该指针以写入正确的对象。

对于任何类型 T ,如果要修改函数参数的值,需要进行如下操作:

void foo( T *param )
{
  *param = ...;
 }

 void bar( )
 {
   T obj;
   foo( &obj );
 }

在此特定实例中,Tchar ** .

关于c - 在c中传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18387797/

相关文章:

arrays - 将字符串拆分为数组并对每个字符 Swift 执行特定操作

java - 解析 HashMap 中的字符串数组

c - 使用topup函数

c - 为什么我的指针不能访问结构的成员元素

c - 将嵌套结构指针分配给嵌套结构

c - 有没有办法用 i387 fsqrt 指令获得正确的舍入?

c - 无法检测到第二次机会异常?

c - 为什么 GCC 允许可变大小数组的静态内存分配?

c - 这是什么定义声明?

java - java中从数组中删除元素