c - 在 C 中使用指针通过引用修改数组

标签 c pointers malloc

<分区>

我是 C 语言开发的新手,在函数中设置数组值并返回调用方法时遇到问题。函数本身必须返回一个 int 并且数组大小需要是动态的,所以我试图使用指向数组的指针更新原始数组。我的代码如下:

int getArray(TestType *testArray)
{

    testArray = malloc(2 * sizeof(TestType));
    testArray[0].id = 1;
    testArray[0].testFloat = 1.5;
    testArray[1].id = 2;
    testArray[1].testFloat = 2.5;

    printf("getArray element 2 id = %d\n", testArray[1].id);

    return 1;
}

void main()
{
   TestType *testArray; 
   int i = getArray(*&testArray);   
   printf("main element 2 id = %d\n", testArray[1].id); 
}

当我运行它时,我得到以下结果:

getArray element 2 id = 2
main element 2 id = 0

我已经看过别处,虽然 c returning an array from a function描述了一个类似的问题,这是处理一个字符数组,而我有一个用户定义的结构,所以不要相信我可以应用相同的解决方案。

最佳答案

在您的代码中,testArray 本身是按值传递的。对函数内部所做的任何更改都不会反射(reflect)给调用者。您需要传递 testArray 的地址,即使用指向指针的指针。

在这种情况下,

  printf("main element 2 id = %d\n", testArray[1].id); 

main() 中基本上是在访问调用 undefined behavior 的无效内存.

但是,你可以做类似的事情

int getArray(TestType **testArray)
{

    *testArray = malloc(2 * sizeof(TestType));
    (*testArray[0]).id = 1;  
    //....
    //....

 int i = getArray(&testArray);

获得所需的行为。

就是说,getArray(*&testArray);getArray(testArray); 相同

关于c - 在 C 中使用指针通过引用修改数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38876014/

相关文章:

c - 我在运行程序时遇到段错误(核心转储)

c++ - 使一维指针数组指向二维 vector 中的对象

c - 为什么在 C 中出现 double free 或 corruption 错误?我释放了我的 mallocs

在 Ubuntu 上针对 libusb-dev 进行编译

c - 为什么在将 malloc 与结构值一起使用时出现 -Wsign-conversion 编译器警告?

c - 在分配它的 void 函数之外释放内存

c - 使用指针执行 strcat 时出现段错误(核心已转储)

c - 在 C 中实现隔离内存存储 (malloc)

c - 保存一个结构以供后期获取

C++ 指向函数的指针作为参数。数据类型不兼容