What's new

Function return a pointer in C

Fever

Active member
Staff member
I am new to C and I try to create a function return a pointer. I used different ways to do it:

1.

typedef struct student{
int age;
}student;

student *create_student(){
student* s;
s-> age= 24;
return s;
}

int main() {
student* s = create_student();
printf("the student age is %d", s->age);
return 0;
}


It compiles but doesn't seem to work.

2.

typedef struct student{
int age;
}student;

student *create_student(){
student* s;
student s2;
s2.age = 24;
s = &s2;

return s;
}

int main() {
student* s = create_student();
printf("the student age is %d", s->age);
return 0;
}


It seems to work, and print "the student age is 24", but if I added one printf statement before previous printf:

int main() {
student* s = create_student();
printf("This is a test\n");
printf("the student age is %d", s->age);
return 0;
}


It gives me:

This is a test

the student age is -1422892954

3.

If I use following ways:

typedef struct student{
int age;
}student;

student *create_student(){
student* s = malloc(sizeof(student));
s -> age = 24;
return s;
}

int main() {
student* s = create_student();
// printf("This is a test\n");
printf("the student age is %d", s->age);
return 0;
}


It works in both cases, with and without the commented printf

I just want to know what are the reasons it fails for 1 and 2. And why it works for 3? And generally speaking when should we use malloc and when we shouldn't?

Thanks

Continue reading...
 
Top