【C】Re06 数组与指针
一、指针和数组
void pointerAndArray() { int array[5] = {1, 2, 3, 4, 5}; printf("pointer array -> %p\n", array); printf("pointer *array -> %d\n", *array); printf("pointer array + 1 -> %p\n", array + 1); printf("pointer *array + 1 -> %d\n", *(array + 1)); // 访问数组首个元素的方式 printf("first element -> %d\n", array[0]); printf("first element -> %d\n", *array); // 如果是指定索引值的元素,就可以根据索引值推进 printf("index is 2 element -> %d\n", array[2]); printf("index is 2 element -> %d\n", *(array + 2)); // 中括号的本质是 *(指针 + 推进值) // 还可以索引值和指针交换书写 [不推荐这样书写] printf("exchanged 3 -> %d\n", array[3]); printf("exchanged 3 -> %d\n", 3[array]); // 遍历 for (int i = 0; i < 5; ++i) { printf("use [] -> %d, use *() -> %d\n", array[i], *(array + i)); } // 数组解引用: // &array[0] == &*(array + 0) == &*array == array; // 注意,不要把指针当成绝对是数组的首个元素的索引 printf("this array byte size is -> %d\n", sizeof(array)); } int main() { pointerAndArray(); return 0; }
二、通过指针操作数组
void usePointerControlArray () { int array[5] = {5, 4, 3, 2, 1}; int * pointer = array; for (int i = 0; i < 5 ; ++i) { printf("array element -> %d, or use *() -> %d\n", pointer[i], *(pointer + i)); } // p 和 array的区别? printf("sizeof pointer -> %d\n", sizeof(pointer)); printf("sizeof array -> %d\n", sizeof(array)); // 使用负数非法访问数组,越界访问 printf("what is before the mem-value -> %d\n", array[-1]); } int main() { usePointerControlArray(); return 0; }
测验1:
void testPA() { int array[5] = {1,2,3,4,5}; int * pointer = array; printf("%d\n", *pointer ++); // 首先解析*p 然后p++ 运算 printf("%d\n", (*pointer) ++); // 首先解析*p 然后*p++ 运算 printf("%d\n", *(pointer ++)); // *pointer 推进 p++ for (int i = 0; i < 5; ++i) { printf("array[%d] -> %d\n", i, array[i]); } } int main() { testPA(); return 0; }
测验2:
void nestingUsage() { int array[10] = {1,2,3,4,5,6,7,8,9,10}; printf("%d\n", array[*(array + *(array + array[3]))]); } int main() { nestingUsage(); return 0; }
三、指针数组
数组的每一个元素的数据类型为指针;
#include <stdio.h> void pointerArray() { int n1 = 10, n2 = 20, n3 = 30, n4 = 40; int * arr[4] = { &n1, &n2, &n3, &n4 }; for (int i = 0; i < 4; ++i) { printf("var-addr -> %p, var -> %d, use *() -> %d\n", arr[i], *arr[i], **(arr + i)); } // ----------------------------------------------------------- char * array[4] = {"aaa", "bbb", "ccc", "ddd"}; int len = sizeof(array) / sizeof(char *); for (int j = 0; j < len ; ++j) { printf("%s\n", array[j]); } } int main() { pointerArray(); return 0; }
四、指针运算
void operatePointer() { int array[10] = {1,2,3,4,5,6,7,8,9,10}; int * p1 = array; int * p2 = &array[4]; // printf("p1 + p2 = %d\n", p1 + p2); // 就算是同指针类型,也不能直接进行算术运算? printf("p1 + p2 = %d\n", (int)p1 + (int)p2); // 将int指针类型强制转换成int类型 指针相加无意义 printf("p2 - p1 = %d\n", p2 - p1); // 指针相减有意义 ,可以获取到间隔的数值 也就是一开始的索引值 // 相乘无意义 // 相除无意义 // 判断运算 if (p1 == NULL) { // true 1 / false 0 // todo... 是空指针 } else { // 不是空指针 } } int main() { operatePointer(); return 0; }