C: String Element of Struct not retaining assigned value
I'm having a bit of a bizarre issue with C.
I have a .c file implementing a structure, and another using it. The
structure in question is basic info about a student (name and grade). The
Implementation file has the functions
initialize
read name
read grade
free memory (delete instance)
the main file goes as follows:
int main (void){
char inBuff[30];
char* name = NULL;
int grade;
Student Stu;
printf("main: Please enter the name\n");
fgets(inBuff, 30, stdin);
name = malloc((sizeof(char)+1)*strlen(inBuff));
strncpy (name, inBuff, 20);
printf("main: Please enter the grade\n");
scanf("%d", &grade);
InitializeStudent (name, grade, &Stu);
/*value testing*/
printf("main: %s\n", Stu.name);
printf("main: %d\n", Stu.grade);
printf ("main: The student's name is %s\n", NameOfStudent(Stu));
printf ("main: The student's grade is %d\n", GradeOfStudent(Stu));
FreeStudent(&Stu);
free (name);
return 0;
}
printf statements in the InitializeStudent function seem to show the
values being assigned correctly. However, both Stu.name and
NameOfStudent(Stu) return "ASCII", and Stu.Grade and GradeOfStudent(Stu)
return 2675716 (which seems to be a memory address) regardless of input.
Of note is the fact that it has been specified that NameOfStudent and
GradeOfStudent be pass-by-value rather than using a pointer (ie a copy of
the struct should be made and passed in to the functions) and have char*
and int return types respectively, whereas InitializeStudent is passed a
pointer and is a void function.
Also possibly important, the name field of Student is initialized as
char name[20];
rather than
char* name;
No comments:
Post a Comment