Common data type bytes
Types of | 16th | 32nd | 64th |
---|---|---|---|
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-bit compiler: char *: 2 bytes
32-bit editor: char *: 4 bytes
64-bit editor: char *: 8 bytes
The difference between const int * p and int * const p is analyzed using code:
#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;
}
Add three situations
Case 1: int * p pointer to const int i1 constant
#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;
}
Output answer:
The value of i1 has not changed.
#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;
}
Output:
The reason is currently unknown.
Case 2: const int * pi pointer points to const int i1
The two types are the same and can be assigned as shown in the following program. i1 cannot be modified by pi and i1.
#include <iostream>
using namespace std;
int main() {
const int i1 = 20;
const int *p;
p = &i1;
cout << *p << endl;
return 0;
}
Case 3: Use const int * const p1 to declare a pointer
#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;
}
The pointer variable itself is in a memory address like other variables. We can also make a pointer point to this address.
short int *p;
short int ** pp; declares a pointer variable pp, which is used to store (or point to) the address of a pointer variable of type short int *.
pp = & p; is to assign the address of p to pp.
example:
#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;
}
The output is: