我正在学习非常基础的 C 类(class),但遇到了问题。我的代码应该获取某人的信息,创建个人资料,然后在最后打印信息。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef struct record
{
char lastname[30];
char firstname[30];
int id;
char gender;
int monthOfBirth;
int dayOfBirth;
int yearOfBirth;
} HealthProfile;
void setID(HealthProfile *HPP){
int id;
printf("please enter your ID: ");
scanf("%d", &id);
HPP->id=id;
}
void setGender(HealthProfile *HPP){
char gender;
printf("please enter yomeur M or F for your gender: ");
scanf("%c",&gender);
HPP->gender=gender;
}
void setFirstName(HealthProfile *HPP){
char firstname[30];
printf("please enter your first name: ");
scanf("%s",&firstname);
HPP->firstname=firstname;
}
void setLastName(HealthProfile *HPP){
char lastname[30];
printf("please enter your last name: ");
scanf("%s",&lastname);
HPP->lastname=lastname;
}
void setDoB(HealthProfile *HPP){
int dayOfBirth;
printf("please enter your DoB: ");
scanf("%d", &dayOfBirth);
HPP->dayOfBirth=dayOfBirth;
}
void setMoB(HealthProfile *HPP){
int monthOfBirth;
printf("please enter your MoB: ");
scanf("%d", &monthOfBirth);
HPP->monthOfBirth=monthOfBirth;
}
void setYoB(HealthProfile *HPP){
int yearOfBirth;
printf("please enter your YoB: ");
scanf("%d", &yearOfBirth);
HPP->yearOfBirth=yearOfBirth;
}
int main()
{
HealthProfile *HPP;
HPP=(HealthProfile*) malloc(sizeof(HealthProfile));
setID(HPP);
setGender(HPP);
setLastName(HPP);
setFirstName(HPP);
setDoB(HPP);
setMoB(HPP);
setYoB(HPP);
printf("\n Profile information.....");
printf("ID number: %d\n", HPP->id);
printf("Gender: %c\n", HPP->gender);
printf("Name: %s/n",HPP->firstname);
printf(" %s", HPP->lastname);
printf("Month of birth: %d\n", HPP->monthOfBirth);
printf("Day od birth: %d\n", HPP->dayOfBirth);
printf("Year of birth: %d\n", HPP->yearOfBirth);
}
给我错误的部分是这两行:
**HPP->lastname=lastname;**
和
**HPP->firstname=firstname;**
每当我尝试运行它时,等号都会突出显示为红色,并且我的代码给出“分配给具有数组类型的表达式”错误。即使在查找并尝试了近两个小时后我还是无法弄清楚,所以有人可以帮助我吗?
最佳答案
字段 HPP->lastname
和 HPP->firstname
都是数组,并且正如错误消息所述,您不能直接分配给数组。
将一个字符串复制到另一个字符串的方法是使用 strcpy
函数:
strcpy(HPP->firstname, firstname);
当然,您可以完全删除副本并直接读入目标数组而不是临时数组。
scanf("%s", HPP->firstname);
关于c - 对具有数组类型错误的表达式进行赋值,无法将 char 数组值设置为结构中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60219984/