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

标签 c struct malloc fibonacci memoization

这里我有一个结构:

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/

相关文章:

c++ - ffi.C 缺少所有符号的所有声明

c - 重新分配(): invalid next size error in C program

c - 预响应参数 WTSSendMessage

c - C中的这个指针是什么?

c - 如何为结构体的字段动态分配内存?

c - 试图将结构成员复制到 c 中的字节数组

c - 如何直接比较数组中的第一个和第二个元素?

Python 结构大小不匹配

c - 使用 malloc 扩展数组

malloc 之后调用 free() 会导致意外行为