Your code is fine, readable and simple, except for the typos. Just make sure you use the same type for i
and j
as that of n
and m
.
#define N 10
#define M 10
int array[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++)
array[i][j] = 0;
}
The advantage of writing the code this way is it works for both a flat 2D array int array[M][N]
and an array of arrays int *array[M]
as well as a pointer to an array of arrays int **array
.
If the array is a flat 2D array of integers and the value is 0
, there is an alternative:
memset(array, 0, sizeof(array[0][0]) * M * N);
But it only works for very specific values that are represented in memory with identical bytes in all positions. Such is the case for 0
and -1
for regular two's complement architectures and 254 other less obvious values (out of 4 billion).
You could also intialize a single row and copy that to the following ones...
Such optimisations are confusing, error prone and unnecessary as modern optimizing compilers will generate very efficient code for this:
#define M 10
#define N 10
void clear_matrix(int array[M][N]) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++)
array[i][j] = 0;
}
}
Notes:
- Code correctness always beats optimisation: what is the purpose of getting incorrect results fast?
- Always benchmark and profile before you optimize, and focus first on the bottlenecks that stand out as obvious targets.
- It is unlikely for the matrix intialization to be the bottleneck. If is it, your algorithm is probably at fault.
- Finding a better algorithm, with reduced complexity, is a more productive effort than micro-optimisation.