I am allocating memory for array of pointers to structure through malloc and want to initialize it with zero like mentioned below . Assuming the structure contains member of type int and char [] (strings) ? so how can i zero out this struct.
Code : suppose i want to allocate for 100
struct A **a = NULL;
a = (struct **)malloc(sizeof( (*a) * 100);
for(i=1; i < 100; i++)
a[i] = (struct A*)malloc(sizeof(a));
Also please explain me why is it necessary to initialize with zero .
Platform : Linux , Programing language : C
I know we can use memset or bzero . I tried it bt it was crashing , may be i was noy using it properly so pls tell me the correct way .
First,
Carrays are zero-based, not one-based. Next, you are allocating only enough space to hold one pointer, but you are storing 100 pointers into it. Are you trying to allocate 100As, or are you trying to allocate 100 sets of 100As each? Finally, themallocinside your loop allocates space for thesizeof a, notsizeof (struct A).I’ll assume that you are trying to allocate an array of 100 pointers to
A, each pointer pointing to a singleA.Solutions: You could use
calloc:Or, you could use
memset:You ask “why is it necessary to initialize with zero?” It isn’t. The relevant requirement is this: you must assign a value to your variables or initialize your variable before you use them for the first time. That assignment or initialization might be zero, or it might be
47or it might be"John Smith, Esq". It just has to be some valid assignment.As a matter of convenience, you might choose to initialize all of your members of
struct Ato zero, which you can do in one single operation (memsetorcalloc). If zero is not a useful initial value for you, you could initialize the structure members by hand, for example:As long as you never refer to the value of an uninitialized and unassigned variable, you are good.