【问题标题】:C - passing argument 1 of 'strcmp' makes pointer from integer without a castC - 传递'strcmp'的参数1使指针从整数而不进行强制转换
【发布时间】:2017-03-29 15:08:30
【问题描述】:

我的函数搜索列表要求用户输入学生 ID 并列出该学生 ID 和姓名。 这是我的结构:

struct student {
    int ID;
    char name[40];
    struct student *next;
};
typedef struct student Student;

这是我的功能:

void searchlist(Student *SLIST){
    Student *currentstudent = SLIST;
    char str[10], str2[10];

    printf("Enter a student ID: ");
    while(currentstudent != NULL){
        scanf("%d", &str);
        if(strcmp(str, (char)currentstudent->ID) == 0){
            printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
        }
    }
}

但是,当我尝试编译时,它给了我一个警告:传递 'strcmp' 的参数 1 使指针从整数而不进行强制转换

【问题讨论】:

  • 请忽略 str2[10]。忘记拿出那部分了。
  • 你想比较什么?因为看起来您正在尝试将字符串 (char[]) 的值与 char 进行比较,而不是另一个字符串 ...

标签: c linked-list strcmp


【解决方案1】:

您没有将正确类型的变量传递给这些函数

    scanf("%d", &str);

这期望 str 是一个 int 但它是一个字符串。

    if(strcmp(str, (char)currentstudent->ID) == 0){

这需要两个字符串(char *char[]),但第二个参数是 int,而您将其转换为 char

既然您正在阅读 int 并希望将其与 int 进行比较,为什么不这样写:

int in_id;
scanf("%d",&in_id);
if(in_id == currentstudent->ID) {

【讨论】:

    【解决方案2】:

    strcmp 签名如下所示:

    int strcmp(const char *s1, const char *s2);
    

    即第二个参数必须是const char* 类型。但是你给它一个char。因此,您会收到错误消息(char 是“整数”类型)。


    另外,scanf("%d", &str); 请求scanf 读取一个整数并将其存储到str。但是str 不是整数类型。 (如果您启用了编译警告,编译器会捕捉到这一点。)


    你需要这样的东西:

    printf("Enter a student ID: ");
    int givenID;
    scanf("%d", &givenID); // read integer input to integer variable
    
    while(currentstudent != NULL) {
        if(currentstudent->ID == givenID) { // check whether this user has the ID entered by the user
            printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
            break; // we found what we were looking for, stop the loop
        }
        currentstudent = currentstudent->next; // move on to the next student in the list
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多