1. 關於數組的首地址:
#include <stdio.h>int main(void){ char cs[2][3] = { {'A','B','C'}, {'D','E','F'} }; char *p1,*p2,*p3,*p4; p1 = p2 = p3 = p4 = NULL; /* 下面四個指標都是指向了同一個地址 */ p1 = &cs[0][0]; /* 這個最好理解 */ p2 = &cs[0]; p3 = &cs; p4 = cs; /* 這個最方便 */ printf("%p\n%p\n%p\n%p\n", p1, p2, p3, p4); /* 顯示地址 */ printf("\n%c %c %c %c\n", *p1, *p2, *p3, *p4); /* 顯示內容 */ getchar(); return 0;}
2. 數組其他元素的地址:
例子中, 數組的元素在記憶體中應該是這樣排列的:
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
下面是通過指標的方式擷取數組的第三個元素:
#include <stdio.h>int main(void){ int nums[2][3] = { {11, 12, 13}, {21, 22, 23} }; int *p1,*p2; p1 = p2 = NULL; p1 = &nums[0][2]; p2 = nums; p2 = p2 + 2;// p2 = (int *)nums + 2; /* 或者用這一句替換上面兩行 */ printf("%d, %d\n", *p1, *p2); getchar(); return 0;}
3. 遍曆數組的普通方法:
#include <stdio.h>int main(void){ int nums[2][3] = { {11, 12, 13}, {21, 22, 23} }; int i,j; for (i = 0; i
4. 通過指標遍曆數組:
#include <stdio.h>int main(void){ int nums[2][3] = { {11, 12, 13}, {21, 22, 23} }; int *p = nums; int i; for (i = 0; i
#include <stdio.h>int main(void){ char cs[2][3] = { {'A','B','C'}, {'D','E','F'} }; char *p = cs; unsigned i; for (i = 0; i
#include <stdio.h>int main(void){ char cs[2][3] = { {'A','B','C'}, {'D','E','F'} }; int i; for (i = 0; i
5. 再探數組的指標地址:
#include <stdio.h>int main(void){ char cs[2][3] = { {'A','B','C'}, {'D','E','F'} }; //在本例中(二維數組) // cs 是指向數組 cs[0] 的地址 // *cs 是指向 cs[0][0] 的地址 printf("%p, %p\n", cs, *cs); // **cs 指向 cs[0][0] 的值 printf("%c, %c\n", **cs, cs[0][0]); getchar(); return 0;}
6. 使用指標遍曆三維數組:
#include <stdio.h>int main(void){ char cs[2][2][3] = { { {'A','B','C'}, {'D','E','F'} }, { {'1','2','3'}, {'4','5','6'} } }; int i; int count = sizeof cs / sizeof cs[0][0][0]; for (i = 0; i
7. 遍曆多維陣列還是用指標變數更容易理解:
#include <stdio.h>int main(void){ char cs[2][2][3] = { { {'A','B','C'}, {'D','E','F'} }, { {'1','2','3'}, {'4','5','6'} } }; char *p = (char *)cs; /* 相對上面的例子, 這裡加了類型轉換; 這樣編譯器就沒有提示了 */ int i; int count = sizeof cs / sizeof cs[0][0][0]; for (i = 0; i