So I'd like to ask the following question about some code my friend is asking me about
(所以我想问以下关于我朋友问我的一些代码的问题)
For the most part if I ever find myself working with Arrays I just allow myself to send the array's name as it decays to a pointer for example:
(在大多数情况下,如果我发现自己正在使用Arrays,我只允许自己发送数组名称,因为它会衰减到指针,例如:)
#include <stdio.h>
void foo(int *arr_p)
{
arr_p[0] = 111;
arr_p[1] = 222;
arr_p[2] = 333;
}
int main()
{
int arr[] = {1,2,3};
foo(arr);
printf("%d %d %d", arr[0], arr[1], arr[2]);
}
and as expected this will print 111, 222, 333
(并按预期将打印111、222、333)
However I have a friend who asked me what would happen if for whatever reason I'd like to pass a pointer to a pointer of this array.
(但是我有一个朋友问我,如果出于任何原因我想将指针传递给该数组的指针,将会发生什么。)
#include <stdio.h>
void foo(int **arr_p)
{
*arr_p[0] = 111;
*arr_p[1] = 222;
*arr_p[2] = 333;
}
int main()
{
int arr[] = {1,2,3};
foo(&arr);
printf("%d %d %d", arr[0], arr[1], arr[2]);
}
now this is the code he sent me... it has a segmentation fault and to perfectly honest I can't really figure out why.
(现在这是他发送给我的代码...它有一个段错误,说实话,我真的不知道为什么。)
I'd imagine dereferencing the pointer to the array would leave me with a pointer to the array would it not? (我以为取消引用数组的指针会给我一个指向数组的指针,不是吗?)
ask by crommy translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…