const指针、结构体、结构体变量的定义的初始化及使用、结构体数组、结构体指针(重点)

一、const

1:修饰普通变量,代表只读的意思

const int a=100;//定义了一个只读变量a的值为100

以后在程序中,不能给a赋值了

a=20;//错误的,a只读

例子:

#include <stdio.h>

int main(int argc,char *argv[])

{

    const int a=100;

a=200;

printf("%d\n",a);

return 0;   

}

gcc编译的结果如下

gec@ubuntu:/mnt/hgfs/share/C语言/day11(8.29)/code$ gcc demo.c

demo.c: In function ‘main’:

demo.c:5:2: error: assignment of read-only variable ‘a’(报错,只读,不能修改)

2:const 修饰指针

        (1)const char *str;

        意思是str指向的内存的内容不能通过str来修改

        用来保护str所指向的内容

         (2)char *const str;

        意思是str是只读的变量,str不能指向别的地方

        (3)const char *const str;

        str不能指向别的地方,指向的内存的内容也不能通过str去修改

        (4)例子1:const char *str;即指向可以改,指向的内容不可以改

#include <stdio.h>

#include <string.h>

int main(int argc,char *argv[])

{

    

char buf[20]="hello world";

const char* str=buf;

strcpy(str,"hellokitty"); //错误

     str="hellokitty";//正确

printf("buf=%s\n",buf);

return 0;   

}

//(1)第一种情况

//没有加const修饰,使用strcpy是以修改buf数组里面的内容

//gec@ubuntu:/mnt/hgfs/share/C语言/day11(8.29)/code$ ./a.out

//buf=hellokitty

//(2)第二种情况

//有加const修饰,编译结果如下:

        (5)例子2:char *const str;即指向不能改变,指向的内容可修改

#include <stdio.h>

#include <string.h>

int main(int argc,char *argv[])

{

    

char buf[20]="hello world";

 char* const str=buf;  

//strcpy(str,"hellokitty"); //正确

//*str='w';        //正确

//str="hellokitty";     //错误

printf("buf=%s\n",buf);

return 0;   

}

         (6)例3:const char *const str;即指向不能改,指向的内容也不能改

 #include <stdio.h>

#include <string.h>

int main(int argc,char *argv[])

{

    

char buf[20]="hello world";

const char* const str=buf;

//strcpy(str,"hellokitty");//错误

    //*str='w'; //错误

str="helloki
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值