我正在寻找一个简单的解决方案。我只有一个元素,可以很容易地将它变成一个简单的长整数数组,但将来我会有一个随机数据类型的结构,所以我不想声明一堆单独的随机类型数组,而是想打包数据进入一个结构。
在这段代码中,问题出在 load()
的调用上,但我不知道如何解决。当我在结构变量前面使用 &
时,编译器报告 warning: passing argument 1 of 'load' from incompatible pointer type
。
我期望的输出而不是错误或段错误是:
0= 1
1= 11
我做错了什么?
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
long n;
}a;
void load(a** x){
x[0]->n=1;
x[1]->n=11;
}
int main(void){
a** b=malloc(200);
b[0]->n=2;
b[1]->n=2;
load(&b); //trouble starts here
printf("0= %ld\n",b[0]->n);
printf("1= %ld\n",b[1]->n);
free(b);
return 0;
}
最佳答案
您不需要指向指针的指针。只需使用
a* b=malloc(ELEMENTS * sizeof (a)); // essentially array with nr of ELEMENTS of type a
函数
void load(a* x){
x[0].n=1; // 0th structure object
x[1].n=11; // 1th structure object .. you can access till ELEMENT-th index
}
你可以这样调用它
load(b); // you can directly pass the pointer
关于c - 在 C 中更新结构数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33155428/