首先,抱歉,毫无疑问,此信息存在于 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/