I know that calloc request memory to be used, writes 0 on all the bits and then returns a pointer to it.
My question is: if I use calloc with a structure that contains pointers, will those pointers have the NULL value or do I have to set them to point to NULL?
struct a{
char * name;
void * p;
}* A;
So basically, will name and p point to NULL after I've used calloc with struct a?
Thanks!
The ISO C standard for
calloc
requires it to initialize everything to0
. That means that if you end up veiwing memory allocated bycalloc
as pointers, it will indeed initially contain NULL (0) pointers.Somehow you've gotten a lot of incorrect answers. C does not require the representation of null pointers to be all-zero-bits. Many people mistakenly think it does, since an integer constant expression with value 0, converted to a pointer, becomes a null pointer.
With that said, on all real-world systems, null pointers are all-zero-bits, and
calloc
is a perfectly reasonable way to get a null-pointer-initialized pointer array in the real world.Yes, they will. Similarly if you do this:
all the pointers in the array will be NULL.
R.'s answer is good, but I'd like to add the standard quotes to support this, and show a way to 0 initialize your struct that does, in fact, yield NULL pointers.
From N1548 (C11 draft)
The footnote then says (emphasis added):
While a null pointer is usually represented as all 0 bits, this representation is not guaranteed. To answer your question directly, no you cannot rely on the
calloc()
'd struct's pointers to beNULL
.If you want to set all contained pointers of a dynamically allocated struct to
NULL
you can use the following:C11:
and
C requires you to have at least one element inside the braces, which is why I use
{0}
instead of{}
. The rest of the elements are initialized according to the above rules, which results in null pointers. As far as I can tell, the rules for this are the same in C11 and C99.