简体   繁体   English

C - 为什么我的程序没有输出任何东西?

[英]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.也有用于位置变量的 typedef 结构。

    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).我认为您应该写,strcmp(location, "home") ,因为 location[25] 超出范围并导致 UB(对于 strcmp 的第二次调用也是如此)。

Problem solved by kaylum: scanf("%s", location[25]); kaylum 解决的问题:scanf("%s", location[25]); -> scanf("%24s", location); -> scanf("%24s", 位置); and strcmp(location[25], "home") -> strcmp(location, "home")和 strcmp(location[25], "home") -> strcmp(location, "home")

Inside a declaration, the [25] has a completely different meaning than outside a declaration.在声明内部, [25]的含义与声明外部完全不同。

In the line在行

char location[25];

it means that you are declaring an array of size 25 .这意味着您要声明一个大小为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). [25]表示您要访问数组中的特定元素,在这种情况下是数组中的第 26元素(数组索引从 0 开始计数,而不是 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 .由于该数组只有 25 个字符,因此尝试访问第 26元素将越界访问该数组,从而调用未定义的行为

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.函数scanfstrcmp都需要一个指向数组第一个元素的指针。 Therefore, passing the value of an individual character by writing location[25] or location[0] is wrong.因此,通过写入location[25]location[0]来传递单个字符的值是错误的。 Instead, you should simply write location .相反,您应该简单地编写location That way, the array will decay to a pointer to the first element, ie to &location[0] .这样,数组将衰减为指向第一个元素的指针,即&location[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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