繁体   English   中英

C将char与“\ n”警告进行比较:指针和整数之间的比较

[英]C comparing char to “\n” warning: comparison between pointer and integer

我有以下C代码部分:

char c;
int n = 0;
while ( (c = getchar()) != EOF ){
    if (c == "\n"){
        n++;
    }
}

在编译期间,编译器告诉我

warning: comparison between pointer and integer [enabled by default]

问题是,如果替代"\\n"'\\n'没有警告的。 任何人都可以解释我的原因吗? 另一个奇怪的事情是我根本不使用指针。

我知道以下问题

但在我看来,他们与我的问题无关。

PS。 如果不是char c而是int c ,那么仍然会有警告。

  • '\\n'被称为字符文字,是标量整数类型。

  • "\\n"被称为字符串文字,是一种数组类型。 请注意,数组会衰减为指针,因此您就会收到该错误。

这可能有助于您理解:

// analogous to using '\n'
char c;
int n = 0;
while ( (c = getchar()) != EOF ){
    int comparison_value = 10;      // 10 is \n in ascii encoding
    if (c == comparison_value){
        n++;
    }
}

// analogous to using "\n"
char c;
int n = 0;
while ( (c = getchar()) != EOF ){
    int comparison_value[1] = {10}; // 10 is \n in ascii encoding
    if (c == comparison_value){     // error
        n++;
    }
}

基本上'\\ n'是一个计算为char的文字表达式。 “\\ n”是一个计算指针的文字表达式。 因此,通过使用此表达式,您实际上正在使用指针。

有问题的指针指向一个内存区域,该区域包含一个字符数组(在本例中为\\ n),后跟一个终止字符,告诉代码数组结束的位置。

希望有帮助吗?

暂无
暂无

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

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