Reputation: 3
Motive: Passing struct to functions such as we can reference it and modify its original pointer.
typedef struct thing{
char x;
}thing_t;
#include <stdio.h>
#include <stdlib.h>
void f1(thing_t *bob, thing_t *boby) {
bob->x = 'y';
boby = bob;
printf("f1 boby after: %c\n", boby->x);
}
int main(void) {
thing_t *foo, *foofy;
foo=(struct thing_t*)malloc(sizeof(struct thing));
foo->x = 'x';
printf("foo before: %c\n", foo->x);
f1(foo,foofy);
printf("foo after: %c\n", foo->x);
printf("foofy after: %c\n", foofy->x);
return 0;
}
the output are:
foo before: x
f1 boby after: y
foo after: y
Segmentation fault (core dumped)
as you can see:
boby = bob;
these wont modify pointer foofy, so it wont get any reference. I want foofy->x valued as y. Any help appreciated.
Upvotes: 0
Views: 59
Reputation: 30916
foofy
is pointing to nowhere in main()
. The value it contains is indeterminate (some garbage value). That's why when you tried to access it - it resulted in segmentation fault. Accessing memory that you were not allowed to access.
If you want to make changes to foofy
pass &foofy
or address of foofy
and then make changes to it.
void f1(thing_t *bob, thing_t **boby) {
bob->x = 'y';
(*boby) = bob;
printf("f1 boby after: %c\n", (*boby)->x);
}
You will call it like this
f1(foo,&foofy);
The output will be when these changes are made is
foo before: x
f1 boby after: y
foo after: y
foofy after: y
Also you won't see the changed value of x
for the struct bob
same way.
C is pass by value. That's why in earlier case a copy of the passed argument is the object on which we made changes in the called function. Changes in copy won't make it happen to reflect those changes in the object in main()
.
Few things that you need to do is - 1) Casting the return value of malloc
is not needed. 2) Check the value returned by malloc
in case it returns NULL
handle it separately.
Upvotes: 1
Reputation: 11921
foofy
is structure pointer and it's not initialized , where it's pointing ? that's why below statements is giving seg.fault
.
printf("foofy after: %c\n", foofy->x);
Assign valid address to foofy
first then you can perform foofy->x
Note : when you are calling f1
function , you may thought by catching with thing_t *boby
, foofy
also get initialized, it's not. boby
is local struct pointer and its valid in f1
function only.
Upvotes: 0