c语言的constant pointer vs pointer to constant

const int* ptr; 

declares ptr a pointer to const int type. You can modify ptr itself but the object pointed to by ptr shall not be modified.

const int a = 10;
const int* ptr = &a;  
*ptr = 5; // wrong
ptr++;    // right  

While

int * const ptr;  

declares ptr a const pointer to int type. You are not allowed to modify ptr but the object pointed to by ptr can be modified.

int a = 10;
int *const ptr = &a;  
*ptr = 5; // right
ptr++;    // wrong

Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):

int const  *ptr; // ptr is a pointer to constant int 
int *const ptr;  // ptr is a constant pointer to int

 同理也适用于其他类型指针,比如下边的字符指针指向不可以修改的字符串,而不是指针本身不可更改。

/* test constant string 
 * compile this program without any error.
 * The output of this program is "wow!"
*/

#include 

int main(void)
{
   const char * str1 = "Hello wolrd!";
   char str2[] = "wow!";

   str1 = str2;
   printf("%s",str1);
}

 

你可能感兴趣的:(c&c++)