Home > Software design >  C - Why my program isn't outputing anything?
C - Why my program isn't outputing anything?

Time:01-30

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");
    }

CodePudding user response:

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

CodePudding user response:

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).

CodePudding user response:

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 26th element in the array (arrays indexes start counting at 0, not 1).

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

In both cases, you should simply write location instead of location[25]. That way, the array will decay to a pointer to the first element, i.e. to &location[0]. The functions scanf and strcmp both expect a pointer to the first element of the array.

  •  Tags:  
  • Related