【发布时间】:2017-01-19 08:15:36
【问题描述】:
所以,这是我的代码:
#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 为结构分配名称?错误是:
[错误] 在非结构或联合的内容中请求成员“名称”
【问题讨论】:
-
personPtr=malloc(sizeof(struct person));和personPtr->name[0]=getchar();