开发者

Initialising an array of pointers to structs in C

开发者 https://www.devze.com 2023-03-02 14:59 出处:网络
I have an array of pointers to structs. I want to initialise every element in the array to NULL. I\'m going to use this ar开发者_开发知识库ray to dynamically add and remove entries so I want to be abl

I have an array of pointers to structs. I want to initialise every element in the array to NULL. I'm going to use this ar开发者_开发知识库ray to dynamically add and remove entries so I want to be able to test against NULL to see if that index is empty.

I tried to do it like this:

struct mystructure *cxs[MAXNOCXS];

int cx_init(void)
{
    int i = 0;
    for (i=0; i<MAXNOCXS; i++)
        cxs[i] == NULL;
    return 0;
}

but my compiler tells me:

error: statement with no effect

referring to the line cxs[i] = NULL;

Are arrays of pointers automatically initialised to NULL in C? If not how could I do that?


You are using the == operator instead of the = operator. In practice, instead of assigning NULL to cxs[i] (which is what it would do if you used the assignment operator =) you are comparing each element with NULL and discarding the result of such comparison, thus the warning of your compiler.

Notice that you can initialize more simply your array using the notation

struct mystructure * cxs[MAXNOCXS] = {};

This syntax tells to the compiler to default-initialize1 all the elements of the array (since the braces, that would contain explicit initializers, are empty), which means that pointers get initialized to NULL and arithmetic types to 0.

If your array has "static storage duration" (i.e. it's a global or static variable), you don't need to do anything special because it's already default-initialized.


  1. To the value they would be initialized to if they were static variables (C99, §6.7.8 ¶10, ¶21).

Edit

After reading around, it seems that the C standard, unlike the C++ one, do not support empty initializers. Still, you can always do:

struct mystructure * cxs[MAXNOCXS] = {NULL};

which will initialize the first element with NULL, and let the other elements be default-initialized (again to NULL).


You will notice that your line is cxs[i] == NULL;, and not cxs[i] = NULL; as you intended.

Also, as it appears that your array has been declared at global scope (and therefore has static storage duration), it will have all its elements zero-initialised by default, so the pointers will already all equal NULL. (Note that this most definitely not the case for standard local variables inside functions).


It seems you have a typo in your code and accidentally use comparison operator instead of assignment - that's what compiler tells you about

for (i=0; i<MAXNOCXS; i++)
        cxs[i] == NULL;

should be

for (i=0; i<MAXNOCXS; i++)
        cxs[i] = NULL;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号