I am new to C and would like to create a N x N matrix of zeros (i.e., every element is zero). N is an integer.
Using MATLAB I managed to generate such an array using the code: Array = zeros(N);
However, in C, how would we generate such an array with minimal lines of code?
Thanks in advance.
CodePudding user response:
Just write
T matrix[N][N] = { 0 };
where T
is some type specifier as for example int
.
Such an initialization is allowed if N is an integer constant expression.
Otherwise you need to write
#include <string.h>
//...
T matrix[N][N];
memset( matrix, 0, sizeof( matrix ) );
CodePudding user response:
You can allocate the memory using the calloc
function which usually allocates memory on the heap (which is good if N
is large):
#include <stdlib.h>
//...
int(*dyn)[N] = calloc(N, sizeof *dyn);
// use dyn
free(dyn);