繁体   English   中英

在C语言中将malloc与struct一起使用

[英]Using malloc with struct in C

所以,这是我的代码:

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>

struct person{
    char name[18];
   int age;
   float weight;
};

int main()
{
    struct person *personPtr=NULL, person1, person2;
    personPtr=(struct person*)malloc(sizeof*(struct person));
    assert (personPtr!=NULL);
    personPtr = &person1;                   // Referencing pointer to memory address of person1

    strcpy (person2.name, "Antony");                //chose a name for the second person
    person2.age=22;                                 //The age of the second person
    person2.weight=21.5;                                //The weight of the second person


    printf("Enter a name: ");               
    personPtr.name=getchar();                   //Here we chose a name for the first person

    printf("Enter integer: ");              
    scanf("%d",&(*personPtr).age);          //Here we chose the age of the first person

    printf("Enter number: ");               
    scanf("%f",&(*personPtr).weight);       //Here we chose the weithgt of the first person

    printf("Displaying: ");                                             //Display the list of persons
    printf("\n %s, %d , %.2f ", (*personPtr).name, (*personPtr).age,(*personPtr).weight);           //first person displayed
    printf("\n %s, %d , %.2f",person2.name, person2.age, person2.weight);                       //second person displayed
    free(personPtr);
    return 0;
}

我有两个错误,我不知道为什么。 首先,我不认为我分配了内存,第一个错误在下一行:

personPtr=(struct person*)malloc(sizeof*(struct person));

它说:

[错误]')'标记之前的预期表达式

我得到的第二个错误是在线上

personPtr.name=getchar();

为什么不能使用getchar为结构分配名称? 错误是:

[错误]要求成员“名称”使用非结构或联合的名称

sizeof*(struct person)是语法错误。 编译器将其视为尝试将sizeof运算符应用于*(struct person) 由于您不能取消引用类型,因此编译器会抱怨。 我认为您打算编写以下内容:

personPtr = malloc(sizeof *personPtr);

这是分配personPtr指向的内容的惯用方式。 现在,仅在定义指针的位置指定类型,这是一件好事。 您也不需要malloc转换malloc的结果,因为void*可隐式转换为任何指针类型。

第二个错误是双重的:

  1. name是固定大小的数组。 您不能使用赋值运算符分配给数组。 您只能分配给每个单独的元素。

  2. getchar返回单个字符,而不是您期望的字符串。 要读取字符串,可以使用scanf("%17s", personPtr->name) 17是缓冲区的大小-1,以防止scanf在字符串中添加NUL终止符时防止缓冲区溢出。

暂无
暂无

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

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