Rechem MEG
Rechem MEG

Reputation: 309

How to initialise an array of pointers to NULL that's inside a struct, and the struct is within an array of other structs

So I have a structure that has an array of pointers inside (to another struct). I was trying to initialise that array to NULL but it seems you can't do it in C. How do you initialise the array Rpr to NULL?

I tried to do it the other way like you see in the code below, but it doesnt work.

typedef struct {maillon *Rpr [7];} repere;
repere R[26];

for(int i=0;i<26;i++){
   R[i].Rpr={NULL};
}

it pops some random insignificant errors.

Upvotes: 2

Views: 152

Answers (4)

0___________
0___________

Reputation: 67476

A simple method of

   memset(R, 0, sizeof(R));

Upvotes: 1

melpomene
melpomene

Reputation: 85767

C distinguishes between assignment (which is an expression) and initialization (which is part of the definition of a variable). In particular, the = { ... } syntax is only valid for initialization.

If you want to do this with a separate loop, you need two nested loops (or a lot of repeated code to set all the elements):

for (int i=0; i<26; i++) {
    for (int j = 0; j<7; j++) {
        R[i].Rpr[j] = NULL;
    }
}

Alternatively, just use initialization:

repere R[26] = { { { NULL } } };

Technically this only initializes the first element of the inner array in the struct in the first element of the outer array, but C has no "half-initialized" variables. The rule is that if there's an initializer that doesn't cover all of the variable's fields, they are implicitly set to zero. For pointers that means they're all null pointers.

In fact, this "initialize everything with 0" initializer can be made both shorter and more generic:

repere R[26] = { 0 };

This { 0 } initializer works for other types as well. (Some compilers warn about this construct ("missing braces in initializer" and similar). Those compilers are stupid and need to stop.)

Upvotes: 4

Achal
Achal

Reputation: 11921

As others pointed, Here

maillon *Rpr [7];

Rpr is array of pointers of maillon type and you need to initialize each pointers with NULL. For e.g

for (int i=0; i<26; i++) {
    for (int j = 0; j<7; j++) { /* Rpr is array of 7 pointers, so rotate 7 times */
        R[i].Rpr[j] = NULL; /* initializing each Rpr[index] with NULL */
    }
}

Upvotes: 0

klutt
klutt

Reputation: 31306

You would have to do something like this:

for(int i=0;i<26;i++){
    for(int j=0; j<7; j++)
       R[i].Rpr[j]=NULL;
}

But you can skip the loop completely by writing repere R[26]={0}; That will init the whole memory of the struct to zero, irregardless of how many fields there are or what type they are.

Upvotes: 1

Related Questions