I'm new to C and i currently studying about pointer and struct. But it seems like i have a problem when assigning value into my struct.
This is my code:
#include <stdio.h>
typedef struct
{
char name[30];
int age;
int birth;
}
student;
void record(student *sp);
int main(void)
{
student std1;
record(&std1);
printf("%i, %i %s\n", std1.birth, std1.age, std1.name);
}
void record(student *sp)
{
printf("Name: ");
scanf("%s", sp -> name);
printf("Birth: ");
scanf("%i", &sp -> birth);
printf("Age: ");
scanf("%i", &sp -> age);
}
Run program:
./struct
Name: David Kohler
result:
Birth: Age: 0, 0 David
What i don't understand is when i'm going to assign name into sp->name it immediatly print an unexpected result like that. It's doesn't prompt to enter age and birth.
But when I ran like this, it works:
./struct
Name: Kohler
Birth: 1997
Age: 22
1997, 22 Kohler
So, what do you guys think happen? It seems like it doesn't took very well when i'm entering a full-long name like "David Kohler" instead just "Kohler".
What's the solution if i want to enter a full name? Do i need to use malloc? Thank you.