#include <cstdio> #include <time.h> using namespace std; void test() { char *a = "abc"; printf("%08x %08x ", a, a + 1); } void test1() { int **a = new int*[10]; for (int i = 0; i < 10; i++) a[i] = new int[10]; for (int i = 0; i < 10; i++) { printf("%08x %08x %08x ", a[i], a + i, &a[i]); } printf(" "); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) printf("%08x ", a[i] + j); printf(" "); } printf("%08x ", &a + 1); } void test2() { int *a = new int[3]; int *b = new int[3]; for (int i = 0; i < 3; i++) printf("%08x ", a + i); for (int i = 0; i < 3; i++) printf("%08x ", b + i); } void test3() { int a[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; printf("%d ", sizeof(a)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%08x ", &a[i][j]); } printf(" "); } printf("%08x %08x %08x %08x %08x ", (int*)a[0] + 1, a[0] + 1, a[1], &a[1], a + 1); printf("%08x %08x %08x %08x ", &a, &a[0], &a + 1, &a[0] + 1); printf("%08x %08x %08x %08x ", &a, &a[0], (int **)&a + 1, (int *)&a[0] + 1); int* t1 = (int *)(&a + 1); int* t2 = (int *)t1 - 1; //printf("%08x ", *((int*)(&a + 1) - 1)); //printf("%d ", (int *)((int *)a[3] - 1)); /* int *ptr = (int *)(&a + 1); printf("%d ", *(ptr - 1)); */ } void test4() { int a[2][2][2] = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} }; int *b = (int *)a; for (int i = 0; i < 8; i++) { printf("%d ", b[i]); } } void test5() { struct A { char a[3]; }; A a; A* b = &a; printf("%08x %08x %08x %08x ", &a, &a + 1, b, b + 1); } int main() { //test1(); //test2(); //test3(); //test4(); test5(); while (1); }
需要注意下面几点:
1. 数组名是类型名,可以当成一个数据结构,a[0]可以看成一个int (*p)[n]指向n维数组的指针;
2. 自己在堆中分配的多维指针,每维指针都在堆中占用一定的空间;
3. 栈中的多维数组是用线性排列的,一个挨着一个,而堆中的数组是在堆中依次排放的,而且排放的首地址貌似需要是16的倍数。