开发者

Dereference a pointer inside a structure pointer

开发者 https://www.devze.com 2022-12-25 23:33 出处:网络
I have a structure: struct mystruct { 开发者_Go百科 int* pointer; }; structure mystruct* struct_inst;

I have a structure:

struct mystruct
{
   开发者_Go百科 int* pointer;
};

structure mystruct* struct_inst;

Now I want to change the value pointed to by struct_inst->pointer. How can I do that?

EDIT

I didn't write it, but pointer already points to an area of memory allocated with malloc.


As with any pointer. To change the address it points to:

struct_inst->pointer = &var;

To change the value at the address to which it points:

*(struct_inst->pointer) = var;


You are creating a pointer of type mystruct, I think perhaps you didn't want a pointer:

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:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号