sourcecode

구조 포인터 내부의 포인터 참조 취소

codebag 2023. 8. 16. 22:12
반응형

구조 포인터 내부의 포인터 참조 취소

나는 구조를 가지고 있습니다.

struct mystruct
{
    int* pointer;
};

structure mystruct* struct_inst;

이제 나는 다음이 가리키는 값을 변경하고 싶습니다.struct_inst->pointer.내가 어떻게 그럴 수 있을까?

편집

제가 쓴 건 아니지만,pointer이미 할당된 메모리 영역을 가리킵니다.malloc.

다른 포인터와 마찬가지로.주소를 변경하려면 다음을 가리킵니다.

struct_inst->pointer = &var;

해당 주소가 가리키는 주소의 값을 변경하는 방법

*(struct_inst->pointer) = var;

mystruct 유형의 포인터를 만들고 있습니다. 포인터가 필요하지 않았을 수도 있습니다.

int x;
struct mystruct mystruct_inst;
mystruct_inst.pointer = &x;
*mystruct_inst.pointer = 33;

힙에 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);

언급URL : https://stackoverflow.com/questions/2581769/dereference-a-pointer-inside-a-structure-pointer

반응형