Matrix is ​​not filled with zeros

I was trying to debug my code in another function when I came across this "strange" behavior.

#include <stdio.h> #define MAX 20 int main(void) { int matrix[MAX][MAX] = {{0}}; return 0; } 

If I set a breakpoint on the line return 0; , and I look at local variables with Code :: Blocks, the matrix is ​​not completely filled with zeros. The first line is there, but the rest of the array contains only random garbage.

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

Perhaps because it was a long day, and I was tired, but I could swear I knew that.

I tried to compile various standards (with the Code :: Blocks compiler in the gcc bundle): -std=c89 , -std=c99 , std=c11 , but this is the same.

Any ideas on what's wrong? Could you explain this to me?

EDIT: I specifically ask about the initializer {{0}} .

I always thought that it will fill all columns and all rows to zero.

EDIT 2: I am particularly concerned about Code::Blocks and its gcc kit. Other comments say that the code runs on different platforms. But why does this not work for me?: /

Thanks.

+5
source share
2 answers

I get it.

Even without the optimization flag in the compiler, the debugger information was simply incorrect.

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

Thanks, however, for the comments.

+3
source

Your code should initialize it to zero. In fact, you can simply do int matrix[MAX][MAX] = {}; , and it will be initialized to 0. However, int matrix[MAX][MAX] = {{1}}; will set the matrix [0] [0] to 1, and everything else - 0.

I suspect that you are observing with Code :: Blocks that the debugger (gdb?) Does not quite show you exactly where it breaks in the code - either one or some other side effect from the optimizer. To test this theory, add the following loop immediately after initialization:

`` `int i, j;

 for (i = 0; i < MAX; i++) for (j = 0; j < MAX; j++) printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]); 

`` ``

and see if what it prints is compatible with the debugger output.

I'm going to guess that it might happen that since you are not using a matrix, the optimizer may have decided not to initialize it. To check, disassemble the main one ( disass main in gdb and see if the matrix is ​​really initialized.

-1
source

Source: https://habr.com/ru/post/1235643/


All Articles