Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 4×4 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading