1.
#define NUM 10
2018年3月31日:
Const用法
全局常变量,局部常变量
#include<stdio.h>
int main()
{
const int a = 10;
int b = 0;
int *p = &a;//类型不一致
return 0;
}
答:不能
--------------------Configuration: Cpp1 -Win32 Debug--------------------
Compiling...
Cpp1.cpp
c:\users\75795\desktop\补习班学习笔记\2018年3月31日\cpp1.cpp(8) : error C2440: 'initializing' : cannot convert from'const int *' to 'int *'
Conversion loses qualifiers
执行 cl.exe 时出错.
Cpp1.obj - 1 error(s), 0 warning(s)
2.??以下输出b的值为何是10
//数组大小只能在编译期间确定,故不能是变量
#include<stdio.h>
int main()
{
const int a = 10;
int b = 0;
int *p = (int *)&a;
*p = 100;
b =a;
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n",*p);
return 0;}
编译成目标文件如下:编译期间已经替换
#include<stdio.h>
int main()
{
const int a = 10;
int b = 0;
int *p = (int *)&a;
*p = 100;
b =10
printf("%d\n",a);//实际a的值已经改变,只是编译期间已经将10替换a了(说是const不能改变,只是表面功夫)
printf("%d\n",10);
printf("%d\n",*p);
return 0;}
3.辨析
Const int *p1;
Int const *p2;
Int * const p3;
Const int * const p4
3.关于字符串(以下的区别)
Char a[20] = {“linefdfafga”};//定义字符串变量
Char b[] = {“linefdfafga”};
Char c[] = {‘d’,’c’,’b’,’b’};
Printf(“%s\n”,c);//会越界,因为c里没有\0
Char *p = “linefdfafga”;//字符串常量(在运行期间才能发现错误)
最佳定义方式:
Const char *p = “dfdsfsdfdf”;(在编译期间就能发现错误)
4.能力拓展问题,不允许拓展,但可以收缩(一般不使用强转)
5.野指针问题
Char *str;//野指针,不知道指向内存哪个区域?(解决方法:初始化)
Scanf(“%s\n”,str);