Why do I have values ​​in my array that I did not assign?

#include <stdio.h>

int main(void)
{

    int values[10];
    int index;

    values[0] = 197;
    values[2] = -100;
    values[5] = 350;
    values[3] = values[0]+values[5];
    values[9] = 
    values[5] / 10;
    --values[2];

    for (index = 0; index < 10; index++)
        printf ("values[%i] = %i\n", index, values[index]);

    return 0;
}

Why do I have values ​​in unassigned items 1, 4, and 6-8? I did not assign any values. How can I make it automatically set to 0 when it is empty?

0
source share
4 answers

You did not assign them, so you just get everything that was in memory in these places.

For zero initialization, you can do this:

int values[10] = {0};

Use as an alternative memset.

+6
source

In C, automatic variables are never nullified. You want memset()your array 0to be gone.

+4
source

C99 , (0 int):

int values[10] =
{
    [0] = 197,
    [2] = -100,
    [5] = 350,
    [3] = values[0] + values[5],
    [9] = values[5] / 10
};

/ . , :

--values[2];

, , , , , . C11:

, , , ; 151)

151) , , .

( , , )...

, , , , 350 - 1 .

+3

, "".

, main() , . , main() , . , . , , . , , Lager, .

+3

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


All Articles