首页 > 解决方案 > 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

标签: cpointersstruct

解决方案


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].


推荐阅读