Reputation: 2368
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 array 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?
Upvotes: 0
Views: 617
Reputation: 126787
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.
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
).
Upvotes: 5
Reputation: 272507
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).
Upvotes: 2
Reputation: 170839
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;
Upvotes: 1