With calloc ()
you allocated for obj
the memory space needed by Std
structure. But with this action you are not allocating the two char *
pointers it contains: name
and surname
.
Accessing them with scanf means writing to undefined location, and this probably leads to a segmentation fault.
So, just malloc ()
to them enough space to contain name and surname:
typedef struct Std{
char* name;
char* surname;
int yearOfBirth;
} Std;
Std* obj = calloc(1, sizeof(Std));
obj->name = malloc(50*sizeof char);
obj->surname = malloc(50*sizeof char);
scanf("%49s", obj->name);
scanf("%49s", obj->surname);
Some notes:
- In C, casting the result of
malloc
is not required. It is instead required in C++, so you can omit it unless you are using a C++ compiler
sizeof char
is 1. I added it to hilight the type ypu are allocating. It can be omitted or otherwise sizeof(obj->name
)` can be used
- With
%49s
I make sure that at most 49 characters + the string terminator are written in my char arrays, avoiding undesirable out of bounds access
As an alternative, you could change the Std
definition in order to statically define the size of name
and surname
char arrays:
typedef struct Std{
char name[50];
char surname[50];
int yearOfBirth;
} Std;
scanf("%49s", obj->name);
scanf("%49s", obj->surname);