1. 擷取數組的地址無須 &, 因為數組名本身就是個地址
#include <stdio.h>int main(void){ char c = 'A'; char cs[] = "ABC"; printf("%c, %s\n", c, cs); /* 擷取字元及字元數組的內容 */ printf("%p, %p, %p\n", &c, cs, &cs); /* 擷取字元及字元數組的地址, cs 與 &cs 沒有區別*/ getchar(); return 0;}
2. 數組元素的地址是連續的:
#include <stdio.h>int main(void){ char cs[] = "ABC"; printf("%p\n%p\n%p\n%p\n", cs, &cs[0], &cs[1], &cs[2]); getchar(); return 0;}
3. 數組名所代表的地址就是第一個元素的地址:
#include <stdio.h>int main(void){ char str[] = "ABC"; char *p1 = str; char *p2 = &str[0]; printf("%p, %p\n", p1, p2); getchar(); return 0;}
4. 通過指標訪問數組元素:
#include <stdio.h>int main(void){ char str[] = "ABC"; char *p = str; printf("%c\n", *p); printf("%c\n", *p+1); printf("%c\n", *p+2); printf("\n"); printf("%c\n", *p); printf("%c\n", *++p); printf("%c\n", *++p); getchar(); return 0;}
5. 通過指標遍曆數組:
#include <stdio.h>int main(void){ char str[] = "123456789"; char *p = str; int i; for (i = 0; i
#include <stdio.h>int main(void){ char str[] = "123456789"; char *p = str; while (*p != '\0') { printf("%c\n", *p); p++; } getchar(); return 0;}
#include <stdio.h>#include <string.h>int main(void){ char str[] = "123456789"; char *p = str; int i; for (i = 0; i
#include <stdio.h>int main(void){ int nums[] = {111,222,333,444}; int *p = nums; int i; for (i = 0; i
6. 注意: 指標+1 是根據元素大小移動一個位置
#include <stdio.h>int main(void){ int nums[] = {111,222,333,444}; int *p = nums; int i; printf("%d\n", *p); printf("%d\n", *(p+1)); printf("%d\n", *p+1); /* 不是這樣; 這是代表取值後再 + 1 */ getchar(); return 0;}
7. 上面的指標其實都是數組元素的指標, 如何聲明真正的數組指標呢?
#include <stdio.h>int main(void){ int nums[4] = {111,222,333,444}; int (*p)[4] = &nums; /* 注意其中的小括弧 */ printf("%d\n", (*p)[1]); /* 用起來並不方便 */ printf("%d\n", (*p)[2]); getchar(); return 0;}