c - 在 C 中更新结构数组失败

标签 c arrays struct segmentation-fault

我正在寻找一个简单的解决方案。我只有一个元素,可以很容易地将它变成一个简单的长整数数组,但将来我会有一个随机数据类型的结构,所以我不想声明一堆单独的随机类型数组,而是想打包数据进入一个结构。

在这段代码中,问题出在 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/

相关文章:

c# - 当您从 C# 中的结构返回 "this"时会发生什么?

c++ - 如何计算下面的struct占用的内存空间?

c - 这个幂函数有什么问题吗?

c - Arduino 读取多个 onewire 传感器

java - 编码bat Array2 ZeroMax

javascript - 如何在javascript中加载二维数组

c - 如何在 Bash C 源代码中实现 Tab 补全

C: const vs no const ..这是怎么编译的?

javascript - 无法连接到数据库-MySQLi错误

c - GCC 将指针转换为不兼容的类型