반응형
C에서 구조물에 대한 포인터를 초기화하는 방법은?
이 구조를 고려할 때:
struct PipeShm
{
int init;
int flag;
sem_t *mutex;
char * ptr1;
char * ptr2;
int status1;
int status2;
int semaphoreFlag;
};
잘 작동합니다.
static struct PipeShm myPipe = { .init = 0 , .flag = FALSE , .mutex = NULL ,
.ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 ,
.semaphoreFlag = FALSE };
하지만 내가 선언할 때는static struct PipeShm * myPipe
, 작동이 안 돼요 교환원과 초기화를 해야 할 것 같아요->
,하지만 어떻게요?
static struct PipeShm * myPipe = {.init = 0 , .flag = FALSE , .mutex = NULL ,
.ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 ,
.semaphoreFlag = FALSE };
구조물에 대한 포인터를 선언하고 구조물과 함께 초기화를 사용할 수 있습니까?
이렇게 할 수 있습니다.
static struct PipeShm * myPipe = &(struct PipeShm) {
.init = 0,
/* ... */
};
이 기능은 "compound literial"이라고 불리며 이미 C99 지정된 초기화기를 사용하고 있으므로 사용자에게 적합합니다.
복합 리터럴의 저장과 관련하여:
6.5.2.5-5
복합 리터럴이 함수 본문 외부에서 발생하면 개체는 정적 저장 기간을 가지며, 그렇지 않으면 엔클로저 블록과 연관된 자동 저장 기간을 갖습니다.
구조체에 대한 포인터를 선언하고 구조체와 함께 초기화를 사용할 수 있습니까?
네.
const static struct PipeShm PIPE_DEFAULT = {.init = 0 , .flag = FALSE , .mutex = NULL , .ptr1 = NULL , .ptr2 = NULL ,
.status1 = -10 , .status2 = -10 , .semaphoreFlag = FALSE };
static struct PipeShm * const myPipe = malloc(sizeof(struct PipeShm));
*myPipe = PIPE_DEFAULT;
네 알겠습니다.
static struct PipeShm myPipeSt = {.init = 0 , .flag = FALSE , .mutex = NULL , .ptr1 = NULL , .ptr2 = NULL ,
.status1 = -10 , .status2 = -10 , .semaphoreFlag = FALSE };
static struct PipeShm * myPipe = &myPipeSt;
먼저 다음과 같이 포인터에 대한 메모리를 할당해야 합니다.
myPipe = malloc(sizeof(struct PipeShm));
그런 다음 아래와 같이 하나씩 값을 할당해야 합니다.
myPipe->init = 0;
myPipe->flag = FALSE;
....
구조물 내부의 각 포인터에 대해서는 메모리를 별도로 할당해야 합니다.
먼저 구조물 초기화 (static struct PipeShm myPipe = {...
). 그럼 주소를 가져갑니다.
struct PipeShm * pMyPipe = &myPipe;
static struct PipeShm * myPipe = &(struct PipeShm) {.init = 0 , .flag = FALSE , .mutex = NULL ,
.ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 ,
.semaphoreFlag = FALSE };
손으로 그 구조물을 만들고, 그것을 가리키는 포인터를 만들어야 합니다.
어느 하나
static struct PipeShm myPipe ={};
static struct PipeShm *pmyPipe = &myPipe;
아니면
static struct PipeShm *myPipe = malloc();
myPipe->field = value;
언급URL : https://stackoverflow.com/questions/11709929/how-to-initialize-a-pointer-to-a-struct-in-c
반응형
'sourcecode' 카테고리의 다른 글
Skipy through pip을 설치할 수 없습니다. (0) | 2023.10.01 |
---|---|
powershell: [ref] 변수에서 호스트 값을 쓰는 방법 (0) | 2023.10.01 |
Android의 CoordinatorLayout에서 다른 보기 아래에 보기 위치 지정 (0) | 2023.10.01 |
InvalidRequestError: VARCHAR에는 방언 mysql의 길이가 필요합니다. (0) | 2023.10.01 |
POST jQuery 배열을 장고에 연결 (0) | 2023.09.26 |