常用数据类型字节数
类型 | 16位 | 32位 | 64位 |
---|---|---|---|
char | 1 | 1 | 1 |
short int | 2 | 2 | 2 |
int | 2 | 4 | 4 |
unsigned int | 2 | 4 | 4 |
float | 4 | 4 | 4 |
double | 8 | 8 | 8 |
long | 4 | 4 | 8 |
long long | 8 | 8 | 8 |
unsigned long | 4 | 4 | 8 |
16位编译器:char*:2个字节
32位编辑器:char*:4个字节
64位编辑器:char*:8个字节
const int *p 与int *const p的区别,使用代码来分析:
#include <iostream>
using namespace std;
int main() {
int i1 = 40;
int i2 = 20;
const int *p;
p = &i1;
p = &i2; //不报错
*p = 80; //报错
//表明如果const在*前面表示*p是常量。
i2 = 80;
cout << *p << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int i1 = 40;
int i2 = 20;
//p = &i1; //报错
int * const p = &i1;
//p = &i2; //报错
*p = 80; //不报错
//表明如果const在*后面表示p是常量。
i2 = 80;
cout << *p << endl;
return 0;
}
补充三种情况
情况一:int *p 指针指向const int i1常量的情况
#include <iostream>
using namespace std;
int main() {
const int i1 = 20;
int *p;
//p = &i1; //报错,const int 类型的i1的地址是不能赋值给指向int类型地址的指针pi的,否
//则pi岂不是能修改i1的值了吗?
p = (int *) &i1;
cout << *p << endl;
*p = 80;
cout << *p << endl;
cout << i1 << endl;
return 0;
}
输出答案:
i1的值没有改变。
#include <iostream>
using namespace std;
int main() {
const int i1 = 20;
int *p;
p = (int *) &i1;
cout << p << endl;
cout << *p << endl;
*p = 80;
cout << p << endl;
cout << *p << endl;
cout << i1 << endl;
cout << &i1 << endl;
return 0;
}
输出:
目前没有搞懂原因。
情况二:const int *pi 指针指向 const int i1的情况
两个类型相同,可以如下程序所示赋值。i1是不可以通过pi和i1来修改的。
#include <iostream>
using namespace std;
int main() {
const int i1 = 20;
const int *p;
p = &i1;
cout << *p << endl;
return 0;
}
情况三:用const int *const p1声明指针
#include <iostream>
using namespace std;
int main() {
int i1 = 20;
int i2 = 10;
const int *const p = &i1;//必须在定义是初始化。
//p = &i2; //报错
//*p = 80; //报错
cout << *p << endl;
return 0;
}
指针变量本身与其它变量一样也是在某个内存地址中的。我们也可以让某个指针指向这个地址。
short int *p;
short int **pp; 声明了一个指针变量pp,这个pp是用来存储(或者指向)一个short int * 类型指针变量的地址。
pp = &p; 就是将p的地址赋给了pp。
例子:
#include <iostream>
using namespace std;
int main() {
short int a;
short int *p;
short int **pp;
a = 10;
p = &a;
pp = &p;
cout << a << endl;
cout << *p << endl;
cout << **pp << endl;
return 0;
}
输出是: