简体   繁体   中英

C - Why my program isn't outputing anything?

I'm very very new in programming, so i don't know how to solve the problem. As you can see, I want to make a program that outputs location that you want. There is, also, typedef struct for location variables.

    char location[25];
    
    printf("Which place info you want? (Home, School): ");
    scanf("%s", location[25]);
    
    if(!strcmp(location[25], "home"))
    {
        printf("%s\n", home.country);
        printf("%s\n", home.city);
        printf("%s\n", home.street);
        printf("%s\n", home.building_number);
    }
    else if(!strcmp(location[25], "school"))
    {
        printf("%s\n", school.country);
        printf("%s\n", school.city);
        printf("%s\n", school.street);
        printf("%s\n", school.building_number);
    }
    else
    {
        printf("I don't have an info about this place\n");
    }

I think you should rather write ,strcmp(location, "home") , because location[25] is out of bounds and causes an UB (same for the second call to strcmp).

Problem solved by kaylum: scanf("%s", location[25]); -> scanf("%24s", location); and strcmp(location[25], "home") -> strcmp(location, "home")

Inside a declaration, the [25] has a completely different meaning than outside a declaration.

In the line

char location[25];

it means that you are declaring an array of size 25 . However, in the lines

scanf("%s", location[25]);

and

if(!strcmp(location[25], "home"))

the [25] means that you want to access a specific element in the array, in this case the 26 th element in the array (arrays indexes start counting at 0, not 1).

Since the array only has 25 characters, attempting to access the 26 th element will access the array out of bounds, invoking undefined behavior .

Even if you weren't accessing the array out of bounds, your code would still be wrong. The functions scanf and strcmp both expect a pointer to the first element of the array. Therefore, passing the value of an individual character by writing location[25] or location[0] is wrong. Instead, you should simply write location . That way, the array will decay to a pointer to the first element, ie to &location[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM