0

Example A: length is some integer variable

int values[length][2];

This array will not have all the elements inside as zeros.

Example B:

int values[10][2];

This one will be all set to zeros.

My main question is how can I make the first one be initialized as zeros?

But, I would like if someone could explain why is the behavior different?

walkman
  • 478
  • 1
  • 8
  • 21
  • 4
    If they are local variables (the first one must be), then *neither* is initiliased to any value. You can explicitly intialise the second one with `int values[10][2] = { 0 };` but not the first. You must use `memset` or loops. – Weather Vane Jun 17 '20 at 17:59

3 Answers3

3

try using calloc it intialises junk of memory to 0's

Nikhil Singh
  • 353
  • 1
  • 17
3

Any variable defined in block scope (i.e. inside of a function or an enclosing block) is not implicitly initialized. It's values are indeterminate. This is the case with both of your examples. Just because the values happened to be 0 doesn't mean they were initialized.

If the array is question is not a variable length array, you could initialize it like this:

int values[10][2] = {{ 0 }};

This explicitly initializes one element of the 2D array to 0, and implicitly initializes the rest to 0.

A VLA however cannot be explicitly initialized. So you should use memset to set the bytes to 0.

int values[length][2];
memset(values, 0, sizeof values);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    Can you do `sizeof values` here? Unknown at compile time. – Weather Vane Jun 17 '20 at 18:02
  • 2
    @WeatherVane Yes, it's a local array, so it gets the size of the array. Also, because it is a VLA, the `sizeof` operator is evaluated at run time instead of compile time. – dbush Jun 17 '20 at 18:04
  • I deleted the comment because i just noticed my mistake... You're completely correct, usage of `memset` does exactly what I was asking for – walkman Jun 17 '20 at 18:09
  • just in another note: Is it indifferent the fact of the array being 2d? Is the behavior to be expected exactly the same in a 1d? @dbush – walkman Jun 17 '20 at 18:13
  • 2
    @walkman That's correct. It applies to *any* variable regardless of type. – dbush Jun 17 '20 at 18:15
  • many thanks for the time! – walkman Jun 17 '20 at 18:17
  • Pedantic, but, the scope does not matter - it just affects the identifier visibility - only the **storage duration matters**. You can **(almost) always** define a variable with static storage duration where you could define one with automatic. The only exceptions that come to mind are for loop initialization and function parameters. – Antti Haapala -- Слава Україні Jun 17 '20 at 19:59
0

the thing is, it might be initialized by 0's if you are lucky and depending on the compiler you use. The easiest might be:

memset(values, '\0', sizeof(int) * length * 2);