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

What is the new content of an array if I redefine a value of an array inside that same array in C?

What are the contents of a[]?

int a[ ] = {4 , 9, 1, 8, [0]=5, 7};

I tried printing it out with:

int main () {
    int a[ ] = {4 , 9, 1, 8, [0]=5, 7};

    for(int i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }

    return 0;
}

The result:

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

5
7
1
8
-1558310176 
712 

While the answer choices available are:

a) 5, 9, 1, 8, 7
b) 4, 9, 1, 8, 5, 7
c) 5, 4, 9, 1, 8, 7
d) 4, 9, 1, 8, 7
e) 4, 9, 1, 8, 0, 5, 7

>Solution :

When an initializer is given for an aggregate type (i.e. an array, struct, or union), the initializer for the subobjects are applied in order.

Given this initializer:

int a[ ] = {4 , 9, 1, 8, [0]=5, 7};

Array elements 0 – 3 are first initialized with the values 4, 9, 1, 8 respectively. Then the designated initializer [0]=5 initializes array element 0 to 5, overwriting the prior initialization of 4. This then makes the current subobject element 0, so the next initializer applies to the next object after that, which is index 1. Then causes index 1 to be initialized with the value 7, overwriting the prior initialization of 9.

So the above initializer creates an array of int of 4 elements initialized with the values 5, 7, 1, 8.

Also, given that you’re printing 10 elements when the array only contains 4, you invoke undefined behavior when attempting to read past the end of the array.

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