1

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");
    }
hsl
  • 39
  • 5

3 Answers3

2

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

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
hsl
  • 39
  • 5
2

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.

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, i.e. to &location[0].

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
1

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

Chi_Iroh
  • 11
  • 1
  • 3
    This answer only mentions one of the two problems that were mentioned in the comments section. The other problem is equally important to fix. – Andreas Wenzel Jan 29 '22 at 20:40