zoukankan      html  css  js  c++  java
  • C和指针 第三章 指针常量与常量指针

    c语言中声明常量的两种方式

    const   int   value
    int   const   value
    

    如果要声明常量的指针,即指向常量的指针,则可以参考上面的常量声明修改一下

    const   int   *ptr
    int   const   *ptr
    

    把*ptr看成一个整体,那么*ptr中的ptr就是指向常量的指针了。顾名思义,指向常量的指针,那么就不可以通过这个指针去修改这个值了。

    #include <stdio.h>
    
    int main(){
    
    	int val = 123;
    	int const *ptr = &val;
    
    	*ptr = 111;
    
    	return 0;
    }
    
    会报错:
    error: read-only variable is not assignable
            *ptr = 111;
            ~~~~ ^
    1 error generated.
    

    但仍可以通过其他方式修改这个量的值。例如

    #include <stdio.h>
    
    int main(){
    
    	int val = 123;
    	int const *ptr = &val;
    	val = 222;
    
    	printf("%d
    ", *ptr);
    
    	return 0;
    }
    输出:222
    

    常量指针的意义就是不可以通过这个指针去修改它所指向的值

    指针常量

    可以理解为先定义一个常量,并且这个常量为指针类型。

    int val = 123;
    int * const ptr = & val;

    ptr只是一个常量,它的值是一个固定的内存地址。

    #include <stdio.h>
    
    int main(){
    
    	char *message = "hello, world
    ";
    
    	//此处ptr是"hello,world
    "的内存地址
    	char * const ptr = message;
    	printf("%s
    ", ptr);
    
    	//就算修改了message的值,也没有修改ptr的值,ptr依旧指向 "hello, world
    "
    	message = "hello, maomao
    ";
    	printf("%s
    ", ptr);
    
    	return 0;
    }
    
    输出
    hello, world
    
    hello, world
    

    指向常量的常量指针

    char const  *  const ptr;
    

    该指针为常量,同时不可以通过该指针修改指向的值。

  • 相关阅读:
    牛式个数
    查找矩阵中某一元素
    破碎的项链
    找鞍点
    方阵形对角矩阵
    间接寻址
    Oracle安装配置的一些备忘点
    通过二维码在Windows、macOS、Linux桌面和移动设备之间传输文件
    httpd连接php-fpm
    nginx反代+lamp+MySQL主从同步的简单实现
  • 原文地址:https://www.cnblogs.com/yangxunwu1992/p/5763206.html
Copyright © 2011-2022 走看看