int * const랑 const int*, int const *는 뭐가 다른가요?

조회수 4990회

발생하는 문제 및 실행환경

  • int * const
  • const int*
  • int const *

는 뭐가 다른가요?

포인터 너무 어려워요 ㅜㅜ

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    const가 누구를 수식하느냐가 달라집니다.

    int * const : int형을 가리키는 const 포인터 - const가 pointer에 붙음.

    int myint = 3;
    int *const myptr = &myint;
    

    같이 선언한 경우, myptr로 myint의 값을 바꿀 수 있으나 myptr이 myint외에 다른 값을 가리키는 것은 불가능합니다.

    예를 들어

    int main(void) {
        int myint1 = 3, myint2 = 5;
        int *const myptr = &myint1;
    
        printf("myptr의 값 = myint1의 주소값 : %p\n", myptr);
    
        /*가능*/
        *myptr = 4; //myint값 : 3->4
    
        /*불가능*/
        myptr = &myint2;
    }
    

    출력 : myptr의 값 = myint1의 주소값 : 0x7fff5fbff76c

    여기서 myptr의 값 0x7fff5fbff76c는 const입니다. 하지만 주소 0x7fff5fbff76c안에 들어있는 값을 바꾸는 것은 가능합니다.

    const int * & int const * : const int를 가리키는 포인터 - const가 int에 붙음

    int myint = 3;
    const int * myptr = &myint;
    

    같이 선언한 경우, myptr로 myint의 값을 바꿀 수 없으나 myptr이 myint외에 다른 값을 가리킬 수 있습니다.

    예를들어

    int main(void) {
        int myint1 = 3, myint2 = 5;
        const int *myptr = &myint1;
    
        printf("myptr의 값 = myint1의 주소값 : %p\n", myptr);
    
        /*가능*/
        myptr = &myint2;
        printf("myptr의 값 = myint2의 주소값 : %p\n", myptr);
    
    
        /*불가능*/
        //*myptr = 4;
    
    }
    

    출력 :

    myptr의 값 = myint1의 주소값 : 0x7fff5fbff76c
    myptr의 값 = myint2의 주소값 : 0x7fff5fbff768
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)