Reputation: 2789
typedef struct _X
{
int a;
int b;
}X;
X** arrayOfXPointers;
arrayOfXPointers = malloc( 10 * sizeof(X*));
I have something like the code shown above.
I know that I have to allocate the individual arrayOfXPointers
array elements.
My question is that before I do this, will arrayOfXPointers[0]
, arrayOfXPointers[1]
etc be null or point to some junk value.
How can I check if an individual array element has been allocated previously or not, given that its value can be junk. Is there a way to dynamically initialise all the array elements as null?
From the answers using calloc
seems to be the best bet, but is not guaranteed by the C standard
Another idea which came to mind, is running a loop and assigning arrayOfXPointers[i]
to be NULL
Is there any other better portable method?
Upvotes: 0
Views: 91
Reputation: 2373
As you using malloc
elements of array will have some junk values. If you want them to be NULLs you can use calloc instead which is actually malloc
+ memset
which zero-initializes the allocated piece of memory.
Edit:
As @rmartinjak mentioned, standard does not guarantee that NULL
will be represented as all-bits-zero, but it's defined as ((void *)0)
by most C standard library implementations
In order to check if an individual array element is null or not you just check it
if (arrayOfXPointers[0] == NULL)
BTW NULL
definition is in <stddef.h>
, so don't forget to include it.
Upvotes: 2
Reputation: 9474
From malloc() man page.
The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. So it may be NULL or some garbage value. If you concerned with content as NULL, calloc()
is better option.
Upvotes: 1
Reputation: 1955
It will have junk in the memory.
To check if pointer is NULL do:
if (pointer==NULL)
or more idiomatically if (!pointer)
.
Upvotes: 2
Reputation: 15121
My question is that before I do this, will arrayOfXPointers[0], arrayOfXPointers[1] etc be null or point to some junk value.
They could be NULL, could have junk values, could also be a mix of both.
How can I check if an individual array element is null or not
Something like if (arrayOfXPointers[0] == NULL)
should be enough.
Upvotes: 0