【问题标题】:Initialization from incompatible pointer type warning从不兼容的指针类型警告初始化
【发布时间】:2020-01-20 09:53:11
【问题描述】:

我正在尝试创建一个指向 stuct 的指针数组。 到目前为止,我已经完成了以下代码

#include <stdlib.h>


typedef struct ID{
    char firstName[21];
    char lastName[21];
    char phoneNumber[11];
}ID;

int main(int argc, char *argv[]) {
    int answere,i=0;
    printf("******* WELCOME TO PHONEBOOK **********\n\n\n");
    printf("***************************************\n");
    printf("*                MENU                 *\n");
    printf("*                                     *\n");
    printf("* 1.Add New   2.Print list     3.Exit *\n\n");
    printf("***************************************\n\n");
    ID* ptr=(int*)malloc(21*sizeof(ID));
    do
    {
        printf("Please select (1, 2 or 3): ");
        scanf("%d",&answere);
        if(answere!=1 && answere!=2 && answere!=3)
        {
            printf("//...Error...\\ please give me a correct answere: ");
        }
        if(answere == 1)
        {
            i++;
            addNew(&ptr,i);
        }
        else if(answere==2)
        {
            PrintList(&ptr,i);
        }
    }while(answere!=3); 

    return 0;
}

所以 ptr 数组将是每次新用户时,我希望它最多 3 个用户添加新用户的代码如下

ID addNew(ID *ptr,int i){
    char fname,lname,phone;
    if(i<3)
    {   
        int l;
        for (l=1;l<=3;l++)
        {
            ID user;
            ptr[l] = user;
            printf("enter the first name:   ");
            scanf("%s",&fname);
            *ptr->firstName= fname;
            printf("enter the last name:    ");
            scanf("%s",&lname);
            *ptr->lastName = lname;
            printf("enter the phone number: "); 
            scanf("%s",&phone);
            *ptr->phoneNumber = phone;
        }
    }
    else
    {
        printf("sorry but you have reach max capacity\n");  
    }
}

问题是,当我在赋值后调用第一个函数时,程序崩溃了。怎么了?

【问题讨论】:

  • 为什么问题本身没有提到你的问题的标题?您实际上是在问哪个问题?

标签: c arrays pointers data-structures


【解决方案1】:

你函数原型ID addNew(ID *ptr,int i),所以你必须用addNew(ptr,i)调用它,而不是使用&amp;ptr,因为你已经将ptr声明为ID*

希望对你有帮助。

【讨论】:

    【解决方案2】:

    您将字符串扫描成单个字符。这可能会导致内存溢出,因此您的程序的行为是未定义的

    scanf("%s",&fname); // here fname is only 1 char long, probably a mistake
    

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2021-06-27
      • 2011-09-01
      相关资源
      最近更新 更多