Hey,

When quick googling didn't really clarify, I'd like to ask here.

When declaring an N-dimensional array, 2D in this case, how to set them all to zero? For 1D arrays it should work with

type name[n] = {0};

Is the same approach also guaranteed to work for N-Dimensional arrays and does it matter if they are with non-constant values or with them? (i.e. char buf[20][n] <-> char buf[20][10]; )

And if they can't be made completely zero with that, how do you suggest making them zero? Are 2D arrays with constant sizes always "behind" each other? (in one continuous block of memory?)

Nick

2
Contributors
3
Replies
5
Views
9 Years
Discussion Span
Last Post by Salem

1. Unspecified initialisers default to zero, so `int arr[5] = { 1, 2 /* 0, 0, 0 */ };` 2. The number of { } reflect the dimensionality, so

``````int arr[2][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
};``````

3. Only the left-most dimension can be left empty. The compiler determines the size from the number of initialisers.

``````int arr[][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
};``````

> Are 2D arrays with constant sizes always "behind" each other?
Arrays are always contiguous within the same dimension.
However, it is a slight assumption that array[1][0] follows array[0][N-1]

So basically you're saying that even when the sizes are constant, I can't memset the whole 2D array like this:

``````char buf[20][10];
memset(buf, 0, sizeof(char) * 20 * 10);``````

?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.