Reputation: 193
I am not sure where am I going wrong with the following structure in C. Can you guys let me know What am I doing wrong and what would be the best approach.
#include<stdio.h>
#include<string.h>
typedef struct
{
char *name;
float gpa;
int courseNo;
} STUDENT;
void createStudent(STUDENT s, char *n, float gpa, int course);
int main(void)
{
struct STUDENT s;
createStudent(s, "Dummy", 3.8f, 203);
printf("Name = %s\n", s.name);
printf("GPA = %3.1f\n", s.gpa);
printf("Course No. = %d\n", s.courseNo);
return 0;
}
void createStudent(STUDENT s, char *n, float gpa, int course)
{
strcpy(s.name, n);
s.gpa = gpa;
s.courseNo = course;
}
Upvotes: 0
Views: 159
Reputation: 1
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int age;
char branch[10];
char gender;
};
struct student s1;
s1.age=18;
strcpy(s1.name:"viraaj");
printf("name of student 1:%s\n",s1.name);
printf("age of student 1:%d\n",s1.age);
return 0;
}
Upvotes: 0
Reputation: 75649
Try this instead:
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
typedef struct
{
char *name;
float gpa;
int courseNo;
} STUDENT;
void createStudent(STUDENT* s, char *n, float gpa, int course);
int main(void)
{
STUDENT s;
createStudent(&s, "Dummy", 3.8f, 203);
printf("Name = %s\n", s.name);
printf("GPA = %3.1f\n", s.gpa);
printf("Course No. = %d\n", s.courseNo);
return 0;
}
void createStudent(STUDENT* s, char *n, float gpa, int course)
{
s->name = malloc((strlen(n)+1) * sizeof(char));
strcpy(s->name, n);
s->gpa = gpa;
s->courseNo = course;
}
Upvotes: 1
Reputation: 14323
You are passing the STUDENT
object by value, not by reference, so any changes that you make to it in your createStudent
function do not effect s
. Pass a pointer instead.
Normally whenever you pass a variable to a function, the variable's value is copied into the appropriate argument. This argument variable, however, is a separate variable from the one you passed however. By using pointers, you are essentially telling the function the identity of your variable, rather than just what value it holds.
As @simonc pointed out, there is one more problem in your code. When you call strcpy
in your function, the pointer you are writing to (s.name
) is unitialized, meaning that when you assign to its data via strcpy
you are overwriting random memory, which is just asking for problems. You should allocate the memory with malloc
before writing to it.
Here is the completed code:
void createStudent(STUDENT *s, char *n, float gpa, int course)
{
s->name = malloc(strlen(n) + 1); // +1 for null terminator
strcpy(s->name, n);
s->gpa = gpa;
s->courseNo = course;
}
And then call it like this:
createStudent (&s, other args ... )
Note that you should deallocate the memory when you are done like so:
free(s.name);
but only when you don't plan on using the object any more.
Upvotes: 3