#include <stdio.h>
void
foo (int (*ptr)[10]) {
(*ptr[0])++;
(*ptr[1])++;
(*ptr[4])++;
}
int
main(int argc, char **argv) {
int i;
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foo(&arr);
for (i = 0; i < 10; i++) {
printf ("%d ", arr[i]);
}
printf ("\n");
return 0;
}
vm@ubuntu:~/src/tcpip_stack$ gcc test.c
vm@ubuntu:~/src/tcpip_stack$ ./a.out
2 2 3 4 5 6 7 8 9 10
*** 检测到堆栈崩溃 ***:终止
中止(核心转储)
如何通过 foo() 中的数组指针访问数组的各个元素? 这里看起来,在 foo() 中,基于数组索引,整个数组被跳转了与索引值一样多的次数。
最佳答案
您取消引用ptr
不正确,因此您访问不存在的 int[10]
s(出界)。
更正:
void foo(int (*ptr)[10]) {
(*ptr)[0]++;
(*ptr)[1]++;
(*ptr)[4]++;
}
这符合operator precedence上面写着 ptr[0]
表示第一个int[10]
(没关系),
ptr[1]
表示第二个 int[10]
和ptr[4]
表示第五个int[10]
,然后您取消引用并尝试增加其中的第一个元素。您必须首先取消引用 ptr
( (*ptr)
),然后使用下标运算符。
++
[]
数组下标
*
这意味着您的代码相当于
void foo(int (*ptr)[10]) {
(*(ptr[0]))++; // increase the first element in the first (only) int[10]
(*(ptr[1]))++; // undefined behavior
(*(ptr[4]))++; // undefined behavior
}
关于arrays - 如何通过数组指针访问数组的各个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73804141/