C语言 取消引用结构指针内的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2581769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dereference a pointer inside a structure pointer
提问by Federico klez Culloca
I have a structure:
我有一个结构:
struct mystruct
{
int* pointer;
};
structure mystruct* struct_inst;
Now I want to change the value pointed to by struct_inst->pointer. How can I do that?
现在我想改变指向的值struct_inst->pointer。我怎样才能做到这一点?
EDIT
编辑
I didn't write it, but pointeralready points to an area of memory allocated with malloc.
我没有写它,但pointer已经指向分配了malloc.
回答by Arkku
As with any pointer. To change the addressit points to:
与任何指针一样。要更改它指向的地址:
struct_inst->pointer = &var;
struct_inst->pointer = &var;
To change the valueat the address to which it points:
要更改它指向的地址处的值:
*(struct_inst->pointer) = var;
*(struct_inst->pointer) = var;
回答by Brian R. Bondy
You are creating a pointer of type mystruct, I think perhaps you didn't want a pointer:
您正在创建一个 mystruct 类型的指针,我想您可能不想要一个指针:
int x;
struct mystruct mystruct_inst;
mystruct_inst.pointer = &x;
*mystruct_inst.pointer = 33;
Of if you need a mystruct pointer on the heap instead:
如果您需要在堆上使用 mystruct 指针:
int x;
struct mystruct *mystruct_inst = malloc(sizeof(struct mystruct));
mystruct_inst->pointer = malloc(sizeof(int));
*(mystruct_inst->pointer) = 33;
/*Sometime later*/
free(mystruct_inst->pointer);
free(mystruct_inst);

