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

Thanks in advance,
Nick

Recommended Answers

All 3 Replies

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

?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.