本文实验环境:Linux x86-64,gcc (GCC) 11.2.0
1 2 3 4 5 6 7
| #include <stdio.h>
int main() { int arr[5] = { 1, 2, 3, 4, 5 }; printf("&arr[0] = %p,\t arr[0] = %d\n", &arr[0], arr[0]); printf("arr = %p,\t\t *arr = %d\n", arr, *arr); }
|
arr
是一个指针变量,其值为数组中首个元素的地址
1 2 3 4 5 6 7
| #include <stdio.h>
int main() { int arr[5] = { 1, 2, 3, 4, 5 }; printf("arr = %p,\t\t *arr = %d\n", arr, *arr); printf("arr + 1 = %p,\t *(arr + 1) = %d\n", arr + 1, *(arr + 1)); }
|
arr + 1
是将指针arr
向后移动 1 个位置,指向数组的下一个元素
- 由于数组元素的数据类型为 int,且
sizeof(int) == 4
- 所以
- 若
printf("%d", arr);
输出 0x7fffcf5000c0
- 则
printf("%d", arr + 1);
输出 0x7fffcf5000c4
1 2 3 4 5 6 7
| #include<stdio.h>
int main() { int arr[5] = { 1, 2, 3, 4, 5 }; printf("arr = %p,\t arr + 1 = %p\n", arr, arr + 1); printf("&arr = %p,\t &arr + 1 = %p\n", &arr, &arr + 1); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include<stdio.h>
void printPtr(void * ptr) { printf("ptr = %p, *ptr = %016lx\n", ptr, *(long *)ptr); }
int main(int argc, char * argv[]) { printPtr(argv); printPtr(&argv);
char * arr[5]; printPtr(arr); printPtr(&arr); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| void foo(int brr[], int len) { for (int i = 0; i < len; i ++) { brr[i]++; } }
void main() { int arr[] = { 1, 2, 3 }, len = sizeof(arr) / sizeof(arr[0]); foo(arr, len); for (int i = 0; i < len; i ++) { printf("%d ", arr[i]); } printf("\n"); }
|
(完)