相关疑难解决方法(0)

如何正确比较字符串?

我试图让一个程序让用户输入一个单词或字符,存储它,然后打印它,直到用户再次键入它,退出程序.我的代码看起来像这样:

#include <stdio.h>

int main()
{
    char input[40];
    char check[40];
    int i=0;
    printf("Hello!\nPlease enter a word or character:\n");
    gets(input);
    printf("I will now repeat this until you type it back to me.\n");

    while (check != input)
    {
        printf("%s\n", input);
        gets(check); 
    }

    printf("Good bye!");


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是我不断打印输入字符串,即使用户输入(检查)与原始(输入)匹配.我比较错误吗?

c string strcmp

168
推荐指数
6
解决办法
41万
查看次数

字符串文字的C优化

刚刚在gdb中检查以下内容:

char *a[] = {"one","two","three","four"};
char *b[] = {"one","two","three","four"};
char *c[] = {"two","three","four","five"};
char *d[] = {"one","three","four","six"};
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:

(gdb) p a
$17 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p b
$18 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p c
$19 = {0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four", 0x80961b7 "five"}
(gdb) p d
$20 = {0x80961a4 "one", 0x80961ac "three", 0x80961b2 "four", 0x80961bc "six"}
Run Code Online (Sandbox Code Playgroud)

我真的很惊讶字符串指针对于相同的单词是相同的.我原以为每个字符串都会在堆栈上分配自己的内存,无论它是否与另一个数组中的字符串相同.

这是某种编译器优化的示例,还是这种字符串声明的标准行为?

c string gcc compiler-optimization string-pool

22
推荐指数
2
解决办法
3746
查看次数

标签 统计

c ×2

string ×2

compiler-optimization ×1

gcc ×1

strcmp ×1

string-pool ×1