简体   繁体   中英

Printing a member of an array within a struct within a struct?

Here I have a struct:

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;

and this is the struct HugeInteger* within the Memo struct:

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;

My question is how can I access a member of the digits array within the Hugeinteger struct within the Memo struct?

I have malloced all three like so throughout my code:

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;
    }

I have tried for example...

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

...which results in a segmentation fault. How can I implement the above line of code correctly? I really feel like i'm missing something important here. Thanks.

There's a problem right here:

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

(Besides the syntax error that I fixed which I assume was a copy/paste error) The second line above replaces the memory address you just allocated with NULL. So that when you do this:

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

You're writing to a NULL address.

You want to leave out the NULL assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM