[질문] const 포인터가 헷갈립니다.

kknd345의 이미지

const int * pOne;
int * const pTwo;
const int * const pThree;

위에 3개가 무슨 차이인가요?
책에 설명이 대충 되어 있어서 아무리 봐도 이해가 안 갑니다.

가르쳐주세요.

myueho의 이미지

const int * pOne; // const int 에 대한 포인터
int * const pTwo; // int 에 대한 const 포인터
const int * const pThree; // const int 에 대한 const 포인터
익명 사용자의 이미지

const int * pOne; //pOne의 형을 재지정 할수 없음
int * const pTwo; //pTwo의 값을 재지정 할수 없음
const int * const pThree; //pThree의 형과 값을 재지정 할수 없음.

죠커의 이미지

kknd345 wrote:
const int * pOne;
int * const pTwo;
const int * const pThree;

위에 3개가 무슨 차이인가요?
책에 설명이 대충 되어 있어서 아무리 봐도 이해가 안 갑니다.

가르쳐주세요.

const int * pOne; // pointer to constant int (const int이므로 값을 수정할 수 없습니다.)
int const * pOne; // pointer to constant int (같은 사례)
int * const pTwo; // constant pointer to int (constant pointer to 이므로 가리키는 대상을 바꿀 수 없습니다.)
const int * const pThree; //constant pointer to constant int (가리키는 대상의 변경이나 값의 수정이나 모두 안 됩니다.)
int const * const pThree; //constant pointer to constant int (역시 동일합니다.)

const가 *(pointer to) 앞에 있냐 뒤에 있냐만 중요합니다.

cdpark의 이미지

const int * pOne;
int * const pTwo;
const int * const pThree;

C 언어의 형은 차근차근 생각하면 쉽습니다.

const int a; 일 때, a = 3; 이라고 대입을 할 수 없죠?
마찬가지로 const int *pOne 일 때, (*pOne)이 const int 형이므로, *pOne = 3; 식으로 대입할 수 없습니다. 하지만 pOne 자체에 대한 제약이 없으므로 pOne = &a; 식으로 다른 "const int"형 변수 포인터를 대입할 수 있습니다.

int * const pTwo에서 *pTwo는 int 형이므로 자유롭게 대입 가능합니다. (*pTwo = 3;) 하지만 pTwo 자체는 const의 제한을 받으므로 pTwo = &b; 식으로 다른 주소를 할당할 수 없습니다.

pThree는 두가지 제약 모두 다 받고요.