在C中使用malloc和struct

Nea*_*hai 1 c pointers structure

所以,这是我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我得到两个错误,我不知道为什么.首先,我不认为我分配了正确的内存,第一个错误是在下一行:

personPtr=(struct person*)malloc(sizeof*(struct person));
Run Code Online (Sandbox Code Playgroud)

它说:

[错误]')'令牌之前的预期表达式

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

personPtr.name=getchar();
Run Code Online (Sandbox Code Playgroud)

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

[错误]在非结构或联合的情况下请求成员'name'

Sto*_*ica 7

sizeof*(struct person)是语法错误.编译器将其视为尝试应用sizeof运算符*(struct person).由于您无法取消引用某个类型,因此编译器会抱怨.我想你打算写下面的内容:

personPtr = malloc(sizeof *personPtr);
Run Code Online (Sandbox Code Playgroud)

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

第二个错误是双重的:

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

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