Confused with the char array when scanf

36,956

Well, a 10 character char array won't fit "mangobatao", since it has 10 characters - there's no room for the null terminator. That means you've caused undefined behaviour, so anything could happen.

In this case, it looks like your compiler has laid out str2 before str1 in memory, so when you call scanf to fill str2, the longer string overwrites the beginning of str1. That's why you see the end of what you think should be in str2 when trying to print str1. Your example will work fine if you use a length of 100.

Share:
36,956
user918304
Author by

user918304

Updated on January 02, 2020

Comments

  • user918304
    user918304 over 4 years

    I am confused with one tiny program.

    #include <stdio.h>
    
    #define LEN 10
    
    int main()
    {
        char str1[LEN] = "\0";
        char str2[LEN] = "\0";
    
        scanf("%s", str1);
        scanf("%s", str2);
    
        printf("%s\n", str1);
        printf("%s\n", str2);
    
        return 0;
    }
    

    If my input are:

    mangobatao
    mangobatao123456

    Why should the output be:

    123456
    mangobatao123456

    And not:

    mangobatao
    mangobatao123456

    How has the char array has been allocated in the memory?