c - 写入结构数组

标签 c arrays struct malloc

我有以下代码

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct Example
{
    uint16_t a;
    uint16_t b;
} ExampleStruct;

void derp(struct Example * bar[], uint8_t i)
{
    uint8_t c;
    for(c = 0; c < i; ++c)
    {
        bar[c]->a = 1;
        bar[c]->b = 2;
    }
}

int main()
{
    struct Example * foo;
    uint8_t i = 3;
    foo = malloc(i*sizeof(ExampleStruct));
    derp(&foo, i);
    free(foo);
    return 0;
}

我遇到段错误,所有调试器都告诉我代码由于以下原因停止工作

bar[c]->a = 1;

我尝试将其重新排列为以下所有内容

(*bar)[c]->a = 1;
(*bar[c])->a = 1;
bar[c].a = 1;
(*bar)[c].a = 1;

但没有成功。我究竟做错了什么?我不明白为什么会失败,也不明白为什么 bar[0]、bar[1] 和 bar[2] 的地址彼此相距如此之远,而每个地址只占用 2 个字节。

最佳答案

无需传递&foo。保持简单:

// In a function declaration, it's (almost) always a pointer, not an array.
// "struct Example bar[]" means *exactly* the same thing in this context.
void init(struct Example * bar, int n) {
    int i;
    for (i = 0; i < n; ++i) {
        bar[i].a = 1;
        bar[i].b = 2;
    }
}

int main() {
    int n = 3;
    struct Example * foo = malloc(n*sizeof(struct Example));
    init(foo, n); // passes the address of the array - &a[0] - to init
    printf("The second element is {%u, %u}\n", foo[1].a, foo[1].b);
    free(foo);
    return 0;
}

输出:

The second element is {1, 2}

关于c - 写入结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19647792/

相关文章:

Linux 中的 C 程序读取作为终端参数传递的文件描述符

arrays - 如何检查变量是否为数组?

c - 访问 C 结构中指针的地址

c - char *(arr[5]) 和 char (*arr)[5] 之间的区别

python - numpy in1d 返回不正确的结果?

c++ - 为结构成员分配的内存是连续的吗?如果结构成员是数组怎么办?

c - 我是否创建一个临时 c 结构并通过套接字发送它?

c - 如何将 char 赋值给 int 值?

c - 动态调整矩阵大小会导致段错误

c++ - 在目录中获取目录中的文件列表