Home > Net >  C: Size of array changes scanf
C: Size of array changes scanf

Time:08-07

I'm trying to understand, why does the size of array change the output (input is 10 5). If I set char k[1] then it only prints 5, but if I set char k[2] then if prints 10 5.

This is my code:

#include <stdio.h>
#include <string.h>

int main() {
    char n[10^1000];
    char k[1];

    scanf("%s%s", n, k);

    for(int i=0; i<strlen(n); i  ) {
        printf("%d", n[i]-'0');
    }

    printf(" %d", k[0]-'0');

}

Thanks in advance!

CodePudding user response:

In this declaration

char n[10^1000];

there is used the bitwise exclusive OR operator ^.

From the C Standard (6.5.11 Bitwise exclusive OR operator)

4 The result of the ^ operator is the bitwise exclusive OR of the operands (that is, each bit in the result is set if and only if exactly one of the corresponding bits in the converted operands is set).

So the above declaration is equivalent to

char n[994];

When a string is entered using the conversion specifier s then the function scanf stores also the terminating zero character '\0' in the destination character array.

As a result for this declaration

char k[1];

where there is no space for the terminating zero character '\0' the call of scanf overwrites memory beyond the array that results in undefined behavior.

As for your question then it is seems that the compiler placed the character array n just after the array k. So the terminating zero character is written in the first character of the array n when the array k is declared as shown above with one element and after the call of scanf you have in fact in the memory occupied by the arrays the following

k[0] = '5';
n[0] = '\0';

That is the array n stores an empty string.

CodePudding user response:

#include <stdio.h>
#include <string.h>

int main() 
{
    char n[5]; 
     char k[5];

   int i;

    printf("input for char n is = ");
      scanf("%s", n);
 
      printf("input for char k is = ");
    scanf("%s", k);

     for (i=0; i<strlen(n); i  ) 
    {
        printf("char n is = ");
       printf("%d \n", n[i] -'0');
    }

    printf("char k is = ");
    printf("%d \n", k[0] - '0');

}


// "for" loop initial declaration are allowed only on c99 or c11 mode.
  • Related