日度归档:30 8 月, 2018

C++指针

仅做保留参考个人使用,谁要是能看懂,那就是C++大神了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<typeinfo>
using namespace std;
char s[2010][2010];
int * func1(int a, int b) { return 0; }
int *(*func)(int, int) = func1;
int main() {
    cout << typeid(func1).name() << endl;
    cout << typeid(func).name() << endl;
    auto ptr = &s;
    cout << typeid(&ptr).name() << " " << sizeof(&ptr) << " " << (int)(&ptr + 1) - (int)(&ptr) << endl;
    cout << typeid(ptr).name() << " " << sizeof(ptr) << " " << (int)(ptr + 1) - (int)(ptr) << endl;
    cout << typeid(&s).name() << " " << sizeof(&s) << " " << (int)(&s + 1) - (int)(&s) << endl;
    cout << typeid(s).name() << " " << sizeof(s) << " " << (int)(s + 1) - (int)(s) << endl;
    cout << typeid(*s).name() << " " << sizeof(*s) << " " << (int)(*s + 1) - (int)(*s) << endl;
    cout << typeid(&s[0]).name() << " " << sizeof(&s[0]) << " " << (int)(&s[0] + 1) - (int)(&s[0]) << endl;
    cout << typeid(s[0]).name() << " " << sizeof(s[0]) << " " << (int)(s[0] + 1) - (int)(s[0]) << endl;
    cout << typeid(*s[0]).name() << " " << sizeof(*s[0]) << endl;
    cout << typeid(&s[0][0]).name() << " " << sizeof(&s[0][0]) << " " << (int)(&s[0][0] + 1) - (int)(&s[0][0]) << endl;
    cout << typeid(s[0][0]).name() << " " << sizeof(s[0][0]) << endl;
}

输出结果(找一个好点的编译器,别用g++,输出的Typeinfo没法看):

1
2
3
4
5
6
7
8
9
10
11
12
int * __cdecl(int,int)
int * (__cdecl*)(int,int)
char (* *)[2010][2010] 4 4
char (*)[2010][2010] 4 4040100
char (*)[2010][2010] 4 4040100
char [2010][2010] 4040100 2010
char [2010] 2010 1
char (*)[2010] 4 2010
char [2010] 2010 1
char 1
char * 4 1
char 1

总结:对某类型做sizeof运算,返回的是本类型本身的大小;对某类型指针做加减操作,数值为n,是对其绝对地址加减:对该指针解除引用后的类型的sizeof运算的数值乘以n。