Reputation: 2244
I am trying to reassign a Person pointer in a function called 'nameChanger', what am I doing wrong? how can I reassign a Person
pointer, to point to another Person
?
#include <stdio.h>
#include <string.h>
typedef struct {
int age;
char name[50];
} Person;
void nameChanger(Person ** person);
int main() {
Person brian;
brian.age = 27;
strcpy(brian.name, "brian");
Person * brian_pointer = &brian;
nameChanger(&brian_pointer);
printf("changing name to 'rick' : %s\n", brian_pointer->name); // should be 'rick'
return 0;
}
void nameChanger(Person ** person){
Person rick;
rick.age = 50;
strcpy(rick.name, "rick");
Person * rick_p = &rick;
*person = &rick;
}
Upvotes: 0
Views: 708
Reputation: 134336
The problem here, is rick
is local to the nameChanger
function. Once the function finshes execution, rick
will cease to exist. So, the returned pointer and any reference will be invalid.
You can make rick
a pointer, and allocate memory using malloc()
and family. In that way, the lifetime of the allocated memory will be until the memory is free()
-d, so after returning, the access will be valid.
Upvotes: 3
Reputation: 24910
You need to be aware that your local variable rick
is allocated on the stack frame of function nameChanger()
, when the function returns, the memory is not valid any more, you should not use that address outside the function.
If you need to do that, use malloc()
instead, or declare the variable as global variable outside of any function.
Try understand memory layout of a process, especial about stack & function in your case.
Upvotes: 2