Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize array inside struct in C

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.

like image 839
Namratha Avatar asked Apr 07 '11 09:04

Namratha


2 Answers

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.

like image 113
pmg Avatar answered Sep 24 '22 00:09

pmg


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.

like image 41
Blagovest Buyukliev Avatar answered Sep 23 '22 00:09

Blagovest Buyukliev