在运行时在函数中创建结构数组

标签 c pointers

首先,抱歉,毫无疑问,此信息存在于 SO 上,但我无法找到它。

尝试(但失败了)让我的大脑围绕着我想做的一些指针魔术。在运行时,我想创建一个可以循环访问的结构“数组”。

typedef struct  {
    int length;
    const char* location;
} receipt_info;

void testA()
{
    receipt_info *receipts;
    testB(&receipts);
    printf("Receipt 0 length: %i\n", receipts[0].length); // Displays valid value
    printf("Receipt 1 length: %i\n", receipts[1].length); // Displays invalid value
}

void testB(receipt_info **info)
{
    *info = malloc(sizeof(receipt_info) * 2);
    info[0]->length = 100;
    info[1]->length = 200;
}

在这个例子中,我将它硬编码为 2,但 IRL 它将由外部因素决定。

在这里我应该做些什么不同的事情?

最佳答案

这部分行不通——您正在进行两次取消引用,但顺序错误

info[0]->length = 100;
info[1]->length = 200;

需要

(*info)[0].length = 100;
(*info)[1].length = 200;

关于在运行时在函数中创建结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484716/

相关文章:

c - 如何用零初始化结构的数组字段

c - 如何卸载不间断(浮点异常时继续)模式?

c - sqlite3 auto_vacuum pragma 有缺点吗?

c - 减去两个地址给出错误的输出

c++ - 有一种比使用类来存储将来会收到其值的指针更优雅的方法吗?

C++在函数中分配动态内存 - 新手问题

c - 如何在 execlp 系统调用后打印行

c - 如何在 lua 脚本中检索堆栈中的值?

c - 区分嵌入式 NUL 和 NUL 终止符

objective-c - 从 ObjC 获取 UnsafeBufferPointer