C 中的指针整数字符警告

Pointer Integer Character Warning in C

我写了一个函数来检查两个字符串是否相同。

int sameString (char string1[], char string2[]) {
    int i = 0;
    while (string1[i] == string2[i]) {
        if (string1[i] == "[=10=]" || string2[i] == "[=10=]") {
            if (string1[i] == "[=10=]" && string2[i] == "[=10=]") {
                return TRUE;
            }
            else {
                return FALSE;
            }
        }
        i++;
    }
}

它工作正常。但是,gcc 编译器给出了一些我没有得到的警告。

2.c: In function ‘sameString’:
2.c:10:24: warning: comparison between pointer and integer [enabled by default]
         if (string1[i] == "[=11=]" || string2[i] == "[=11=]") {
                        ^
2.c:10:46: warning: comparison between pointer and integer [enabled by default]
         if (string1[i] == "[=11=]" || string2[i] == "[=11=]") {
                                              ^
2.c:11:28: warning: comparison between pointer and integer [enabled by default]
             if (string1[i] == "[=11=]" && string2[i] == "[=11=]") {
                            ^
2.c:11:50: warning: comparison between pointer and integer [enabled by default]
             if (string1[i] == "[=11=]" && string2[i] == "[=11=]") {
                                                  ^

同样在扫描和保存字符串时,

char operation[8];
scanf ("%s", &operation);

我又收到一个错误,但我没有收到。

2.c: In function ‘main’:
2.c:65:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[8]’ [-Wformat=]
         scanf ("%s", &operation);
         ^

谁能解释一下这些错误是什么?

首先,string1[i]char 类型,您将其与 字符串 "[=13=]" 进行比较。你需要的是

 string1[i] == '[=10=]'

同样如此。

其次,operation很可能是一个数组。您可以将数组名称作为 %s 的参数传递给 scanf(),它会自动衰减到指向数组第一个元素的指针。

您必须使用字符文字而不是字符串文字

  if (string1[i] == '[=10=]' || string2[i] == '[=10=]') {
                    ^^^^                  ^^^^
        if (string1[i] == '[=10=]' && string2[i] == '[=10=]') {
                          ^^^^                  ^^^^
            return TRUE;
        }

字符串文字,例如“\0”,具有字符数组类型。字符串文字“\0”的类型为 char[2],由两个字符 { '\0', '\0' } 组成。 在极少数例外的表达式中,它们被转换为指向其第一个字符的指针,类型为 char *.

考虑到在一般情况下,函数参数应具有限定符 const。

函数内部还有冗余条件

函数可以写的简单一些。例如

int sameString ( const char string1[], const char string2[] ) 
{
    int i = 0;

    while ( string1[i] == string2[i] && string1[i] != '[=11=]' ) i++;

    return string1[i] == string2[i];
}

索引最好使用类型 size_tptrdiff_t.

而不是类型 int

例如

size_t i = 0;

在C语言中,双引号字符串是一个字符串(char的数组),而单引号字符串是单个字符(char):

#include "stdio.h"

int main (int argc, char **argv ) {
  char* s= "foo";

  // this is comparing the character at s[0] to the location  
  // (pointer) of where the string "f" is stored.
  if (s[0] == "f") {
    printf("s[0] is the same as the location of the string f\n");
  }

  // This is comparing the character at s[0] to the character 'f'
  // which is what you're asking to do.
  if (s[0] == 'f') {
    printf("s[0] is the same as the character f\n");
  }
}

gcc 警告您,因为尽管您可以(在不同类型之间)进行这些比较(如果您确实愿意),但几乎可以肯定这不是您的本意。