C语言开发笔记(七)const和指针

const修饰变量是常用的,不容易犯错,而const和指针一起使用时很容易混淆。

(一)const int *p

#include <stdio.h>

int main(void)
{
    int a = 10;
    int b = 20;

    const int *p = &a;

    *p = b;

    return 0;
}

const在int *的左侧,即指针指向内容为常量,所以p指向的内容不允许修改,编译器报错

修改成p = &b后编译通过,因为这是修改指针p本身。

(二)int* const  p

#include <stdio.h>

int main(void)
{
    int a = 10;
    int b = 20;

    int* const p = &a;

    *p = b;

    return 0;
}

const在int*的右侧,即指针本身为常量,所以*p = b是允许的,而*p = &b是不允许的。

(三)const int* const p

通过一二的例子,举一反三,可知两个const分别出现在int *的左右侧,说明p不仅指针本身不能修改,且p指向的内容也不能修改。

猜你喜欢

转载自blog.csdn.net/Dr_Haven/article/details/89737153