struct myStruct
{
short int myarr[1000];//want to initialize all elements to 0
}
How do I initialize the array?
I tried doing short int* myarr[1000]={0}
inside the struct but it's wrong. How can I do this? I don't mind doing it in the implementation file. This struct is contained in a header file.
Use the universal initializer: {0}
.
The universal initializer works for anything and initializes the elements to the proper 0 (NULL
for pointers, 0
for ints, 0.0
for doubles, ...):
struct myStruct example1 = {0};
struct myStruct example2[42] = {0};
struct myStruct *example3 = {0};
Edit for dynamically allocated objects.
If you're allocating memory dynamically use calloc
rather than malloc
.
p = malloc(nelems * sizeof *p); /* uninitialized objects; p[2] is indeterminate */
q = calloc(nelems, sizeof *q); /* initialized to zero; q[2] is all zeros */
With realloc (and possibly other situations) you need to memset
.
If it is declared out of a function (not on the stack), the whole struct will be zeroed at compile time.
Otherwise, you can use memset
after declaring it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With