-1

i need to input name to a variable (first name*) in a struct with a malloc i don't understand why to program is fail to run. im inserting the name (for example David) and its should gets the name and put it in temp array and then to resize the pointer first_name* and copy the string temp to first_name*

someone can help me understand why its doesn't work?

look for the function "ReadPerson".

typedef struct{
    int day, month, year;
}  Date;

typedef struct{
    char *first_name, *last_name;
    int id;
    Date birthday;
}  Person;

void ReadDate(Date *a)
{
    printf("insert day, month, year\n");
    scanf("%d%d%d", &a->day, &a->month,&a->year);
}

void ReadPerson(Person *b)
{
    char temp_first_name[21];
    char temp_last_name[21];

    printf("insert first name:\n");
    gets(temp_first_name);
    b->first_name = (char*)malloc(strlen(temp_first_name)+1);
    strcpy(b->first_name,temp_first_name);
    //need to check malloc (later)

    printf("insert last name:\n");
    gets(temp_last_name);
    b->last_name = (char*)malloc(strlen(temp_last_name)+1);
    strcpy(b->last_name, temp_last_name);
    //need to check malloc (later)

    printf("insert id\n");
    scanf("%d",&b->id);

    printf("insert person's birthday:\n");
    ReadDate(b);
}

Thanks.

  • 1
    Does it even compile? Here: `ReadDate(b);` you pass `b` of type `Person *` to a function that expects `Date *`. – Yuriy Ivaskevych Jan 27 '17 at 13:30
  • Check [here](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) to find why you should not cast return value of `malloc()`. – Quentin Jan 27 '17 at 13:30

1 Answers1

1

i don't understand why to program is fail to run

Well, it's because you're trying to substitute incompatible types and decent compiler should have told you about that.

Let's look at the end of function void ReadPerson(Person *b):

{
    ...
    ReadDate(b);          // error here
}

As you can see b is of type Person * and you pass it to the function void ReadDate(Date *a) which expects a Date * type.

So it is probably a simple typo, just change to this: ReadDate(&b->birthday);.

Yuriy Ivaskevych
  • 956
  • 8
  • 18