gpt4 book ai didi

c - 在结构中打印结构中数组的成员?

转载 作者:行者123 更新时间:2023-11-30 15:47:39 26 4
gpt4 key购买 nike

这里我有一个结构:

typedef struct Memo
{
// dynamically allocated HugeInteger array to store our Fibonacci numbers
struct HugeInteger *F;

// the current length (i.e., capacity) of this array
int length;

} Memo;

这是 Memo 结构中的 struct HugeInteger*:

typedef struct HugeInteger
{
// a dynamically allocated array to hold the digits of a huge integer
int *digits;

// the length of the array (i.e., number of digits in the huge integer)
int length;
} HugeInteger;

我的问题是如何访问 Memo 结构中 Hugeinteger 结构中的数字数组的成员?

我在我的代码中像这样分配了所有三个:

Memo *newMemo = malloc(sizeof(Memo));

newMemo->F = malloc(sizeof(HugeInteger) * INIT_MEMO_SIZE); //in this case 44

for (i = 0; i < INIT_MEMO_SIZE; i++)
{
newMemo->F[i].digits = malloc(sizeof(int*) * 1); //creating an array of size 1 to test
newMemo->F[i].digits = NULL;
newMemo->F[i].length = 0;
}

例如,我尝试过...

newMemo->F[i].digits[0] = 1; 

...这会导致段错误。如何正确实现上面这行代码?我真的觉得我在这里错过了一些重要的东西。谢谢。

最佳答案

这里有一个问题:

newMemo->F[i].digits = malloc(sizeof(int) * 1); //creating an array of size 1 to test
newMemo->F[i].digits = NULL;

(除了我修复的语法错误(我认为是复制/粘贴错误))上面的第二行用 NULL 替换了刚刚分配的内存地址。这样当你这样做时:

newMemo->F[i].digits[0] = 1;

您正在写入 NULL 地址。

您想省略 NULL 赋值。

关于c - 在结构中打印结构中数组的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17254522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com