Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

c - 将数组的指针传递给C中的函数(Passing pointer of an array to a function in C)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This happens because in other words you declare arr as this:

(发生这种情况是因为换句话说,您将arr声明为:)

int arr[3];
arr[0]=1;arr[1]=2;arr[2]=3;
foo(&arr);

Then when you pass the address to foo it is actually a pointer to an array of 3.

(然后,当您将地址传递给foo时,它实际上是指向3数组的指针。)

void foo(int (*arr_p)[3])
{
    *arr_p[0] = 111;
    *arr_p[1] = 222;
    *arr_p[2] = 333;
}

Then arr_p[0] is the first array of 3, arr_p[1] is the second array of 3, and arr_p[2] the thirs.

(然后arr_p [0]是3的第一个数组,arr_p [1]是3的第二个数组,而arr_p [2]是第三个数组。)

They are not individual indices in the one array

(它们不是一个数组中的单个索引)

This would work but it would make no sense:

(这会起作用,但没有任何意义:)

void foo(int (*arr_p)[3])
{
    *arr_p[0] = 111;
    *arr_p[1] = 222;
    *arr_p[2] = 333;
}

int main()
{
    int arr[3][3];
    foo(arr);

    printf("%d %d %d",  arr[0][0], arr[1][0], arr[2][0]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...