[英]passing struct pointer to function doesn't modifiy the references
Motive: Passing struct to functions such as we can reference it and modify its original pointer. 动机:将struct传递给函数,例如我们可以引用它并修改其原始指针。
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. 这些不会修改指针foofy,因此不会获得任何引用。 I want foofy->x valued as y. 我希望foofy-> x的值等于y。 Any help appreciated. 任何帮助表示赞赏。
foofy
is pointing to nowhere in main()
. foofy
指向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. 如果你想改变foofy
通&foofy
或地址foofy
,然后进行更改。
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. 同样,您也不会以相同的方式看到struct bob
的x
更改值。 C is pass by value. C是按值传递。 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()
. 复制中的更改不会使其反映main()
对象中的那些更改。
Few things that you need to do is - 1) Casting the return value of malloc
is not needed. 您需要做的几件事是-1)不需要malloc
的返回值。 2) Check the value returned by malloc
in case it returns NULL
handle it separately. 2)检查malloc
返回的值(如果它返回NULL
,请分开处理。
foofy
is structure pointer and it's not initialized , where it's pointing ? foofy
是结构指针,它没有初始化,它指向的是什么? that's why below statements is giving seg.fault
. 这就是下面的语句给出seg.fault
的原因。
printf("foofy after: %c\n", foofy->x);
Assign valid address to foofy
first then you can perform foofy->x
首先为foofy
分配有效地址,然后您可以执行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. 注意:当您调用f1
函数时,您可能会想通过抓住thing_t *boby
foofy
,而foofy
也被初始化了,不是。 boby
is local struct pointer and its valid in f1
function only. boby
是本地结构指针,仅在f1
函数中有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.