1

I created an array of 10 elements in C inside of main and declared values for only some of the elements. When printing out the array I noticed that one of the elements, which was left untouched, was not initialized to zero. Instead, it was initialized to a different large value every time (i.e. 1491389216). I then commented out all of my code and just left the array as I initially declared it.

When running the code, the first 8 elements of the array were initialized to zero, the 9th element in the array was being initialized to a large value (like 1491389216) which changed every time, and the last element was consistently being initialized to the same non-zero number.

Does anyone have any idea why this is happening?

2
  • 5
    Post your code. minimal reproducible example Commented Jan 15, 2017 at 5:23
  • You mean in C , that i edited ? Commented Jan 15, 2017 at 13:56

1 Answer 1

4

Local (automatic) arrays are not initialized unless you explicitly initialize them. Otherwise they contain whatever random data already occupies the memory.

If you want to zero out all of the elements when declaring the array, you can do this:

int arr[10] = {0};

Or:

int arr[10] = {};

Depending on your compiler (GCC allows this, unless you specify -pedantic).

Or, just use memset() instead:

int arr[10];
memset(arr, 0, sizeof(arr));

Similarly, memory allocated by malloc() — or extended by realloc() — is not initialized; use calloc() to zero-initialize such data:

int *arr = (int*) calloc(10, sizeof(int));
...
free(arr);
Sign up to request clarification or add additional context in comments.

2 Comments

Using calloc function also satisfies i guess
automatic arrays aren't initialized. Static ones are. Fwiw.

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.