Reputation: 8058
I have an array of char pointers in C with a size of 10.
I am trying to loop through and print each string out. Not all of the elements are populated and I believe this is causing me an error. How do I check if an element is populated.
This is what I have tried. When I run my code I find that the first element is populated and the value is printed but then I get an error.
char *errors[10];
ret = doMessages(&h, errors);
for (i = 0; i < 10; i++)
{
if(errors[i] != NULL)
{
printf("%s", errors[i]);
}
}
Upvotes: 1
Views: 2057
Reputation: 437554
You do not explicitly initialize the values in your array to NULL
, so they contain whatever happened to previously exist in the memory location where your array is stored.
To initialize, use something like
char *errors[10] = { 0 };
You could also do the same with memset
:
char *errors[10];
memset(errors, 0, sizeof(errors));
Upvotes: 0
Reputation: 5456
Well, probably only the first element of errors
is been populated. The rest are garbage values (may be NULL, and may be anything), so your check (!=NULL
) doesn't really check that an element has populated.
I suggest you to initialize your array before doMessages
, (something like char *errors[10]={0};
, and then the check errors[i]!=NULL
will make sense.
Upvotes: 0
Reputation: 122001
errors
is not initialised so the elements can be any value, specifically may not be NULL. Change to:
char *errors[10] = { 0 }; /* Initialise all elements to NULL. */
Upvotes: 4