Yarin
Yarin

Reputation: 135

Problem initializing a struct with the {0} initializer

I encountered a bizarre problem while trying to use the {0} initializer on a struct.
The struct I built consists of a 2D array of size 4x4 and was defined as the following:

typedef struct Matrix{
double array[4][4];
} mat;

when I tried to initialize the struct with zero's using the following :

mat MAT_A = {0};

it only initialized part of the struct with zero's, but when I did something like this :

mat MAT_A = {0},MAT_B = {0};

then when I checked the content of MAT_A it was initialized to zero completely, though MAT_B was partly initialized like what was happened at the beginning when I only wrote :

mat MAT_A = {0};

I have no clue why it is happening and I will appreciate any insights.

int main(){
    int i,row = 0;
    mat MAT_A = {0}, MAT_B = {0};
    for (i = 0; i < 16; i++)
    {
        if(i%4 == 0)
            row++;
    
        printf("%f,", *(*(MAT_A.array + row) + i%4));
    }
    
    return 0;
}

Upvotes: 0

Views: 59

Answers (1)

dbush
dbush

Reputation: 223699

You're not printing the result correctly:

printf("%f,", *(*(MAT_A.array + row) + i));

The value of i ranges from 0 to 15, and you're using that value to index the second dimension of the array. That dimension only has size 4 so you're reading past the end of the array. Doing so triggers undefined behavior.

Instead of using i here, use i%4. That will keep the second dimension index in the proper range.

Upvotes: 1

Related Questions