Array storage

1

I have a question about storing information in array, I thought that when inside a loop, an array of size 200, for example char nome[200] it would be filled continuously until no more space is left to save the information, causing the system to return an error, but in some examples I have done, the array is reused in the loop and instead of being "completed" in the space it it still has, it seems that the space that was used has the information replaced, if this really happens, why is the array not completed?

int main()
{
    int n,i;
    char ch;
    int length;
    scanf("%d", &n);
    char abc[200];
    for( i = 0; i < n; i++)
    {
        while( (ch = getchar() != '\n') && ch != EOF);
        fgets( abc,200,stdin);
        length = strlen( abc);
        printf("%d", length);
        printf("%s", abc);
    }
}

This is an example. if I type a sentence of size 100 and then another one of size 100 the second will happen to take the place of the first, instead of completing the other 100 that remained? and if I type one of size 200 and then another of size 100, will replacement occur?     

asked by anonymous 08.03.2017 / 02:17

1 answer

2

Never have empty space in an array. When you declare char abc[200]; , each of the 200 char s within that array has some unknown value.

By C language specification (which is the document that officially describes the C language, published by the ISO ) , when an array is declared this way, as a local variable, its initial value is either not specified, or it is a special value called trap representation , which should not be read or used in the program. In practice, its abc array will initially contain the value that by chance is already in the memory region that the compiler reserves for the variable. The important thing to keep in mind is: there is no concept of the "empty" variable in the C language, so it does not make sense to talk about "completing the array".

In your code, when you call fgets(abc, 200, stdin); , all information that fgets has was what you passed abc , 200 , stdin . In your loop for you call fgets in exactly the same way for n times, so it will behave the same way every time, writing the string from the beginning of the abc array.

When you pass an array to a function that receives a pointer, as is the case with the first parameter of fgets() , what you pass is actually the memory address of the first element of the array. So the two codes below are equivalent:

fgets( abc,200,stdin);

and

fgets(&abc[0],200,stdin);

If you want the string to be written in abc from a given position k ≤ 200, you should call it with:

fgets(&abc[k], 200 - k, stdin);

Why 200 - k in the second argument? Because the second argument says how many positions from the address given in the first argument the fgets() function can use. If you are writing from position k , there are only 200 - k positions from there.

    
08.03.2017 / 07:05