zoukankan      html  css  js  c++  java
  • 常量指针与指向常量的指针

     1 #include<stdio.h>
     2 void main(){
     3         int a = 1;
     4         int const *p1;//指向常量的指针
     5         const int *p2;//指向常量的指针
     6         p1 = &a;
     7         p2 = &a;
     8         *p1 = 2;//企图改变a的值(非法)
     9         *p2 = 2;//企图改变a的值(非法)
    10 
    11         int * const b;//常量指针(常指针)
    12         b = &a;//企图改变b的值。(非法)
    13 }

    编译结果:

    hello.c: In function ‘main’:
    hello.c:8:2: error: assignment of read-only location ‘*p1’
      *p1 = 2;//企图改变a的值(非法)
      ^
    hello.c:9:2: error: assignment of read-only location ‘*p2’
      *p2 = 2;//企图改变a的值(非法)
      ^
    hello.c:12:2: error: assignment of read-only variable ‘b’
      b = &a;//企图改变b的值。(非法)
      ^

    区分技巧:

      首先两者都是指针。看*和const谁离的变量名近:如果const近,那么就是const指针(const=常量嘛,常指针);如果*近,就是指向常量的指针,此时const与int的位置无关。

  • 相关阅读:
    Flask基础
    Scrapy框架(持久化,去重,深度控制,cookie)
    scrapy框架 简易整理
    BeautifulSoup 模块
    requests模块
    复习第三天
    在Django中使用原生Sql
    ajax跨域简单请求和复杂请求
    复习第二天
    IOS
  • 原文地址:https://www.cnblogs.com/airduce/p/9111957.html
Copyright © 2011-2022 走看看