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

C 在运行时在函数中创建结构数组,c,pointers,C,Pointers,首先,我道歉,因为毫无疑问这条信息是存在的,但我很难找到它 试着用我想做的一些指针魔法来缠绕我的大脑,但失败了。在运行时,我想创建一个可以迭代的结构数组 typedef struct { int length; const char* location; } receipt_info; void testA() { receipt_info *receipts; testB(&receipts); printf("Receipt 0 lengt

首先,我道歉,因为毫无疑问这条信息是存在的,但我很难找到它

试着用我想做的一些指针魔法来缠绕我的大脑,但失败了。在运行时,我想创建一个可以迭代的结构数组

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;

这部分不起作用-您正在进行两次解引用,但顺序错误

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

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

我欠你一杯啤酒;谢谢我欠你一杯啤酒;谢谢OT:为什么你对同一件事的命名不同于收据和信息?这样的命名并不容易改进。坚持将类型大写,变量使用小写。像typedef。。。接收信息;它允许您使用一个变量,如Receipe_info Receipe_info;甚至进一步指示指针,例如Receipe_info*precipe_info;和接收信息**接收信息;最后一条规则可能仅仅通过查看代码就可以帮助您发现错误。OT:为什么您对同一事物的命名与收据和信息不同?这样的命名并不容易改进。坚持将类型大写,变量使用小写。像typedef。。。接收信息;它允许您使用一个变量,如Receipe_info Receipe_info;甚至进一步指示指针,例如Receipe_info*precipe_info;和接收信息**接收信息;最后一条规则可能会帮助您通过查看代码来发现错误。