【问题标题】:Initiliasing a character array in C when using structures and functions [duplicate]使用结构和函数时在 C 中初始化字符数组
【发布时间】:2020-06-10 00:20:16
【问题描述】:

我做了一个程序来理解结构的概念并从函数返回结构

struct student
{
    char name[20];
    int age;
    char subject[20];
    int marks;
    int rollno;
}sheet;
struct student display()
{

    sheet.name[20]="Swathi";
    sheet.age=21;
    sheet.subject[20]="Mathematics";
    sheet.marks=85;
    printf("Enter roll no.:");
    scanf("%d",&sheet.rollno);

}
int main()
{   
    struct student sheet1;
    sheet1=display();
    printf("Name:%s",sheet.name);
    printf("Age:%d",sheet.age);

}

我收到 2 条警告消息

warning: assignment makes integer from pointer without a cast [-Wint-conversion]
  sheet.name[20]="Swathi";
warning: assignment makes integer from pointer without a cast [-Wint-conversion]
  sheet.subject[20]="Mathematics";

为什么会这样?我应该如何改变这个?

【问题讨论】:

    标签: c function struct structure


    【解决方案1】:

    这里是:

    sheet.name[20]="Swathi";
    

    只需获取"Swathi" 的地址(只读),将该地址隐式转换为char(使其无用),然后将其分配给sheet.name[20](超出范围,因此未定义)行为)。相反,试试这个:

    strcpy(sheet.name, "Swathi");
    

    sheet.subject[20]="Mathematics"; 也是如此。另请注意,您的 struct student display() 没有返回任何内容,它应该是 void display() 并且不需要 struct student sheet1;

    【讨论】:

    • 与其为这个非常常见的常见问题解答发布另一个答案,不如考虑对其进行近距离投票。可以在C tag wiki 中找到合适的欺骗目标列表。
    【解决方案2】:

    成功了

    struct student
    {
        char name[20];
        int age;
        char subject[20];
        int marks;
        int rollno;
    }sheet;
    struct student display()
    {
    
        strcpy(sheet.name, "Swathi");
        sheet.age=21;
        strcpy(sheet.subject,"Mathematics");
        sheet.marks=85;
        printf("Enter roll no.:");
        scanf("%d",&sheet.rollno);
    
    }
    int main()
    {   
        display();
        printf("Name:%s",sheet.name);
        printf("Age:%d",sheet.age);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多