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; the Student struct definition is as follows:
#define MAXNAMESIZE 20 typedef struct { char name[MAXNAMESIZE]; int grade; } Student; as requested, the code for initialize student is as follows
void InitializeStudent (char *name, int grade, Student *S) { printf ("InitializeStudent: entered initialization\n"); int i = 0; S = malloc (sizeof(Student)); for (i = 0; i< strlen(name); i++) if (name[i] == '\n') name[i] = '\0'; strncpy(S->name, name, 20); S->grade = grade; printf ("InitializeStudent: %s\n", S->name); printf ("InitializeStudent: %d\n", S->grade); }
struct Student. EDIT: right, I noticed the code is indented except you're using tabs. For SO it's better to convert the indentation to spaces in your editor before posting.NameOfStudentandGradeOfStudentimplementations.InitializeStudent (name, grade, &Stu)(sizeof(char)+1)*strlen(inBuff)allocates almost twice what you need. First thing to remember is thatsizeof(char)is always1. Knowing that, you should also know that then it's enough to only allocatestrlen(...) + 1bytes. And in this case it might not even be needed to allocate that string, hard to tell until you show theInitializeStudentfunction.malloc()call and the followingstrncpy()seem unnecessary to begin with, sinceInitializeStudent()has no choice but to copy the value of thenameparameter into the struct member.