I have the following program in C:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct str{
char * s;
int len;
}string;
typedef struct stud{
unsigned int id;
string name;
char gender;
}student;
student* addstud(const int id, const char name[64], const char gender);
student* addstud(void){
char buf[64];
struct stud *sb;
sb = (struct stud*)malloc(sizeof(struct stud));
printf("Enter student ID:\n");
scanf("%d",&sb->id);
printf("Enter student name:\n");
scanf("%s", buf);
sb->name.s = buf;
sb->name.len = (int)strlen(buf);
printf("Enter student gender:\n");
scanf(" %c", &sb->gender);
printf("Student ID: %d, name: %s, gender: %c\n", sb->id, sb->name.s, sb->gender);
return sb;
}
int main(){
student *mystudent;
mystudent=addstud();
printf("Student ID: %d, name: %s, gender: %c\n", mystudent->id, mystudent->name.s, mystudent->gender);
getchar();
return 0;
}
In the addstud()
function, everthing is fine but in main()
when I try to print out the student name from mystudent->name.s
it just garbage data. I don't understand why this could happened as it was clearly fine in addstud()
function and both pointers point to the same memory address :( Could anyone please shred some light what I did wrong here, please? Thank you!
you can duplicate the buf.
sb->name.s = strdup(buf);