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?

1
  • 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. Commented Jun 17, 2020 at 17:59

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

7 Comments

Can you do sizeof values here? Unknown at compile time.
@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.
I deleted the comment because i just noticed my mistake... You're completely correct, usage of memset does exactly what I was asking for
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 That's correct. It applies to any variable regardless of type.
|
3

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

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.