【问题标题】:Printing a member of an array within a struct within a struct?在结构中的结构中打印数组的成员?
【发布时间】:2013-06-19 17:21:10
【问题描述】:

这里我有一个结构:

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 结构中的 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; 

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

【问题讨论】:

    标签: c struct malloc fibonacci memoization


    【解决方案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 赋值。

    【讨论】:

    • 我尝试了你的要求,但在 newMemo->F[i].digits[0] = 1;
    • @mbratch 应该是malloc(sizeof(int) * 1);
    • 不幸的是,同一行仍然存在段错误
    • @KarimElsheikh 是时候启动调试器了。我们不是您的调试器。
    • @Armin 是的很好(+1),我只是盯着那个:) - 我已经相应地改变了它。虽然,sizeof(int*) 至少应该和sizeof(int) 一样大,所以它不会是段错误的原因。
    猜你喜欢
    • 2019-03-03
    • 2017-06-11
    • 1970-01-01
    • 2011-12-19
    • 2016-11-21
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多