Search code examples
cgcccodeblocksc99c89

Matrix not zero-filled on declaration


I was trying to debug my code in another function when I stumbled upon this "weird" behaviour.

#include <stdio.h>

#define MAX 20

int main(void) {
    int matrix[MAX][MAX] = {{0}};

    return 0;
}

If I set a breakpoint on the return 0; line and I look at the local variables with Code::Blocks the matrix is not entirely filled with zeros. The first row is, but the rest of the array contains just random junk.

I know I can do a double for loop to initialize manually everything to zero, but wasn't the C standard supposed to fill this matrix to zero with the {{0}} initializer?

Maybe because it's been a long day and I'm tired, but I could've sworn I knew this.

I've tried to compile with the different standards (with the Code::Blocks bundled gcc compiler): -std=c89, -std=c99, std=c11 but it's the same.

Any ideas of what's wrong? Could you explain it to me?

EDIT: I'm specifically asking about the {{0}} initializer.

I've always thought it would fill all columns and all rows to zero.

EDIT 2: I'm bothered specifically with Code::Blocks and its bundled GCC. Other comments say the code works on different platforms. But why wouldn't it work for me? :/

Thanks.


Solution

  • I've figured it out.

    Even without any optimization flag on the compiler, the debugger information was just wrong..

    So I printed out the values with two for loops and it was initialized correctly, even if the debugger said otherwise (weird).

    Thanks however for the comments