상수 포인터

c or linux 2005. 3. 15. 19:15

void test1( char const * const x )
{
   x++;    // No. 1
   (*x)++;   // No. 2
   return;
}

 

void test2( char const *y )
{
   y++;      // No. 3
   (*y)++;   // No. 4
   return;
}

 

void test3( char * const z )
{
   z++;      // No. 5
   (*z)++;   // No. 6
   return;
}

 

void main( void )
{
    char x;
    test1( &x );
    test2( &x );
    test3( &x );
}

-----------------------------------------------------------------------------------------

1,2,3,6으로 생각했었는데...아니군요...전 지금까지 const에 대해 잘못 알고있었군요...에고...큰일날뻔했네요...

 

'const data_type variable_name' 으로만 해왔었는데, 가끔 'data_type const variable_name'형식으로 되어있는걸 보면 왜 보기 불편하게 이렇게 해놓나 생각했었는데 그 포인터의 경우 그 위치에 따라 결정되는 군요.

 

찾아봤더니 C99엔 다음과 같이 친절히 설명이 되어있더군요. 친절한 설명도 영어의 압박이 '불친절'의 누명을 씌웠지만요^^

 

1) The type designated as "float *" has type "pointer to float". Its type category is pointer, not a floating type. The const-qualified version of this type is designated as "float * const" whereas the type designated as "const float *" is not a qualified type — its type is "pointer to constqualified float" and is a pointer to a qualified type.

 

2) The following pair of declarations demonstrates the difference between a "variable pointer to a constant value" and a "constant pointer to a variable value".


const int *ptr_to_constant;
int *const constant_ptr;


 

The contents of any object pointed to by ptr_to_constant shall not be modified through that pointer, but ptr_to_constant itself may be changed to point to another object. Similarly, the contents of the int pointed to by constant_ptr may be modified, but  constant_ptr itself shall always point to the same location.

 

1) "float *"형은 float의 pointer형으로 명시된다. 이 타입은 float형이 아니라 포인터에 속한다. 이 데이터 타입(float의 pointer형)의 상수형은 "const float *"가 아닌 "float * const"로 명시된다. "const flaot *"은 상수로 제한된 float의 포인터이다.

 

2) 다음 두 쌍의 선언문은 "상수의 포인터변수"와 "변수의 포인터상수"의 다름을 설명한다.

 

const int *ptr_to_constant;
int *const constant_ptr;

 

ptr_to_constant(상수를 가리키는 포인터변수)에 의해 접근되는 어떤 개체의 요소는 그 포인터에 의해 변경될 수 없다. 하지만  ptr_to_constant 자체는 다른 개체를 접근할 수 있도록 변경될 수 있다. 이와 반대로, constant_ptr(포인터상수)가 가리키는 개체는 수정될 것이다. 하지만 constant_ptr 자체는 항상 같은 위치(메모리 상의 주소)를 가리킬것이다.

Posted by '김용환'
,