1

I'm just trying to initialize a dynamically created matrix with zero values:

#include <stdio.h>
#include <stdlib.h>

void writeMatrix (int **m, int size) {
    int i, j;
    for (i=0; i<size; i++) {
        for (j=0; j<size; j++) {
            printf("%i ", m[i][j]);
        }
        printf("\n");
    }
}

int main(void) {

    int i, size;
    scanf("%i", &size);

    int **m;
    m = malloc(size * sizeof(int *));
    for (i=0; i<size; i++) {
        m[i] = malloc(size * sizeof(int));
        m[i] = {0};
    }

    writeMatrix(m, size);

    return 0;
}

But it crashes with this error:

compilation info
prog.c: In function 'main':
prog.c:23:10: error: expected expression before '{' token
   m[i] = {0};
          ^

Isn't this the right way of set all matrix values to zero?

Thanks in advance.

0

2 Answers 2

3

You can't use syntax like m[i] = {0}; unless you're initializing an array at the time it is defined. What you want to use is memset:

memset(m[i], 0, size * sizeof(int));

Or you can use calloc, which allocates memory for an array and zeros it out all at once:

m[i] = calloc(size, sizeof(int));
Sign up to request clarification or add additional context in comments.

2 Comments

In terms of time, is there a difference between these methods? calloc looks faster
@WashingtonGuedes Given that you're allocating and clearing, calloc is definitely the preferred method.
2

No, this is the way to initialize static arrays, not dynamic ones.

In general you can:

  1. Pass through each element of the allocated array of ints and set it to 0.

    for (int j = 0; j < size; ++j) { m [i][j] = 0; }

  2. Use memset to set all the values of the array to 0.

    memset(m[i], 0, size * sizeof(int));

  3. Use calloc instead of malloc which allocates the memory similary to malloc and also sets to 0 all the allocated memory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.