c - How can I point this string to the structure?
问题描述
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char firstName[20];
char lastName[20];
int id;
char gender[10];
int monthOfBirth;
int dayOfBirth;
int yearOfBirth;
} HealthProfile;
void setName(HealthProfile *HP) {
char firstName;
char lastName;
printf("Enter your first and last name: ");
scanf("%s" "%s", &firstName, &lastName);
HP->firstName = firstName;
HP->lastName = lastName;
}
void setID(HealthProfile *HP) {
int id;
printf("Enter ID: ");
scanf("%d", &id);
HP->id = id;
}
void setGender(HealthProfile *HP) {
char gender;
// HealthProfile hp;
// strcpy(hp.gender, &gender);
printf("Enter your gender: ");
scanf("%s", &gender);
HP->gender = gender;
}
void setBD(HealthProfile *HP) {
int monthOfBirth;
int dayOfBirth;
int yearOfBirth;
printf("Enter your month of birth, day of birth and year of birth: ");
scanf("%d" "%d" "%d", &monthOfBirth, &dayOfBirth, &yearOfBirth);
HP->monthOfBirth = monthOfBirth;
HP->dayOfBirth = dayOfBirth;
HP->yearOfBirth = yearOfBirth;
}
int main(){
// pointer declared to HealthProfile structure
HealthProfile *HP;
// pointer initialized using malloc
HP = (HealthProfile*) malloc(sizeof(HealthProfile));
// Calls various functions
setID(HP);
setGender(HP);
setName(HP);
setBD(HP);
// Creates your profile
printf("Creating your Health Profile! \n");
printf("Profile created for: %s\n", HP->firstName);
printf("Lastname: %s\n", HP->lastName);
// prints ID
printf("ID: %d\n", HP->id);
printf("Gender: %s\n", HP->gender);
printf("Month of birth: %d\n", HP->monthOfBirth);
printf("day of birth: %d\n", HP->dayOfBirth);
printf("year of birth: %d\n", HP->yearOfBirth);
}
What I am trying to do is assign HP to a string but I get this error.
array type 'char [10]' is not assignable
HP->gender = gender;
(same error with first and last name of course) So I searched online and found out that char can't be assigned and strcpy should be used instead. As you can see by my failed attempt in the gender function.
Can someone help me fix my errors? Thanks
解决方案
char gender;
- gender
is not an array. It is only one object of type char
.
Thus, HP->gender = gender;
does not work because gender
does not decay to a pointer to char
like an array would do.
Edit it to char gender[10]
.
推荐阅读
- ios - 键入 ListView 的 TextField 元素时,iOS 上的键盘自动隐藏
- javascript - 没有 Node.JS 的 Google Firebase 实时同步?
- python - Flask 服务器事件在开发中工作但不在生产中
- abap - 创建采购申请后触发 IDoc 或 Web 服务
- veeam - Veeam B/up 和 Azure 存储
- oracle - 使用缩写表名时在 Oracle 中转义保留字的语法
- r - gganimate 使用 transition_time 随时间变化,其中时间变量是 NBA 比赛时钟
- git - 将提交的文件恢复到它们在 master 中的版本?
- r - 从浏览器自动化过程下载和摄取文件
- android - 为什么我会收到 espresso.PerformException:在带有 id 的视图上执行“滚动到”时出错?