6
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.

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

Just initialize an instance of the struct with {0}, this will zero your array as well. Alternatively, use memset as NKCSS demonstrates.

Comments

0

int's arn't reference types, don't they get initialized after allocating memory for your structure?

You could just do this: memset(&myStruct, 0, sizeof(myStruct));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.