C语言 C将int数组指针作为参数传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13730786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:41:35  来源:igfitidea点击:

C pass int array pointer as parameter into a function

carraysfunctionpointersparameters

提问by stergosz

I want to pass the B int array pointer into func function and be able to change it from there and then view the changes in main function

我想将 B int 数组指针传递给 func 函数,并能够从那里更改它,然后查看 main 函数中的更改

#include <stdio.h>

int func(int *B[10]){

}

int main(void){

    int *B[10];

    func(&B);

    return 0;
}

the above code gives me some errors:

上面的代码给了我一些错误:

In function 'main':|
warning: passing argument 1 of 'func' from incompatible pointer type [enabled by default]|
note: expected 'int **' but argument is of type 'int * (*)[10]'|

EDIT: new code:

编辑:新代码:

#include <stdio.h>

int func(int *B){
    *B[0] = 5;
}

int main(void){

    int B[10] = {NULL};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);

    return 0;
}

now i get these errors:

现在我收到这些错误:

||In function 'func':|
|4|error: invalid type argument of unary '*' (have 'int')|
||In function 'main':|
|9|warning: initialization makes integer from pointer without a cast [enabled by default]|
|9|warning: (near initialization for 'B[0]') [enabled by default]|
||=== Build finished: 1 errors, 2 warnings ===|

回答by Daniel Fischer

In your new code,

在您的新代码中,

int func(int *B){
    *B[0] = 5;
}

Bis a pointer to int, thus B[0]is an int, and you can't dereference an int. Just remove the *,

B是指向 的指针int,因此B[0]int,并且您不能取消引用int。只需删除*,

int func(int *B){
    B[0] = 5;
}

and it works.

它有效。

In the initialisation

在初始化

int B[10] = {NULL};

you are initialising anintwith a void*(NULL). Since there is a valid conversion from void*to int, that works, but it is not quite kosher, because the conversion is implementation defined, and usually indicates a mistake by the programmer, hence the compiler warns about it.

您正在int使用void*( NULL)初始化 an 。由于有一个从void*to的有效转换int,这是可行的,但它并不完全符合,因为转换是实现定义的,并且通常表明程序员有错误,因此编译器会对此发出警告。

int B[10] = {0};

is the proper way to 0-initialise an int[10].

是 0 初始化 an 的正确方法int[10]

回答by Alberto Bonsanto

Maybe you were trying to do this?

也许你试图这样做?

#include <stdio.h>

int func(int * B){

    /* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
    *(B + 2) = 5;
}

int main(void) {

    int B[10];

    func(B);

    /* Let's say you edited only 2 and you want to show it. */
    printf("b[0] = %d\n\n", B[2]);

    return 0;
}

回答by greggo

If you actually want to pass an array pointer, it's

如果你真的想传递一个数组指针,它是

#include <stdio.h>

void func(int (*B)[10]){   // ptr to array of 10 ints.
        (*B)[0] = 5;   // note, *B[0] means *(B[0])
         //B[0][0] = 5;  // same, but could be misleading here; see below.
}

int main(void){

        int B[10] = {0};   // not NULL, which is for pointers.
        printf("b[0] = %d\n\n", B[0]);
        func(&B);            // &B is ptr to arry of 10 ints.
        printf("b[0] = %d\n\n", B[0]);

        return 0;
}

But as mentioned in other answers, it's not that common to do this. Usually a pointer-to-array is passed only when you want to pass a 2d array, where it suddenly looks a lot clearer, as below. A 2D array is actually passed as a pointer to its first row.

但正如其他答案中提到的,这样做并不常见。通常只有当你想传递一个二维数组时才传递一个指向数组的指针,它突然看起来清晰了很多,如下所示。二维数组实际上是作为指向其第一行的指针传递的。

void func( int B[5][10] )  // this func is actually the same as the one above! 
{
         B[0][0] = 5;
}

int main(void){
    int Ar2D[5][10];
    func(Ar2D);   // same as func( &Ar2D[0] )
}

The parameter of func may be declared as int B[5][10], int B[][10], int (*B)[10], all are equivalent as parameter types.

func 的参数可以声明为int B[5][10], int B[][10], int (*B)[10],都等价于参数类型。

Addendum: you can return a pointer-to-array from a function, but the syntax to declare the function is very awkward, the [10] part of the type has to go after the parameter list:

附录:你可以从函数返回一个指向数组的指针,但是声明函数的语法很笨拙,类型的 [10] 部分必须在参数列表之后:

int MyArr[5][10];
int MyRow[10];

int (*select_myarr_row( int i ))[10] { // yes, really
   return (i>=0 && i<5)? &MyArr[i] : &MyRow;
}

This is usually done as below, to avoid eyestrain:

这通常如下进行,以避免眼睛疲劳:

typedef int (*pa10int)[10];

pa10int select_myarr_row( int i ) {
   return (i>=0 && i<5)? &MyArr[i] : &MyRow;
}

回答by Sunil Bojanapally

In new code assignment should be,

在新的代码分配中应该是,

B[0] = 5

In func(B), you are just passing address of the pointer which is pointing to array B. You can do change in func() as B[i] or *(B + i). Where i is the index of the array.

在 func(B) 中,您只是传递指向数组 B 的指针的地址。您可以将 func() 更改为 B[i] 或 *(B + i)。其中 i 是数组的索引。

In the first code the declaration says,

在第一个代码中,声明说,

int *B[10]

says that B is an array of 10 elements, each element of which is a pointer to a int. That is, B[i] is a int pointer and *B[i] is the integer it points to the first integer of the i-th saved text line.

说 B 是一个包含 10 个元素的数组,其中的每个元素都是一个指向 int 的指针。也就是说,B[i] 是一个 int 指针,*B[i] 是它指向第 i 个已保存文本行的第一个整数的整数。

回答by G_L

Using the really excellent example from Greggo, I got this to work as a bubble sort with passing an array as a pointer and doing a simple -1 manipulation.

使用来自 Greggo 的非常出色的示例,我将其用作冒泡排序,将数组作为指针传递并执行简单的 -1 操作。

#include<stdio.h>

void sub_one(int (*arr)[7])
{
     int i; 
     for(i=0;i<7;i++)
    {
        (*arr)[i] -= 1 ; // subtract 1 from each point
        printf("%i\n", (*arr)[i]);

    }

}   

int main()
{
    int a[]= { 180, 185, 190, 175, 200, 180, 181};
    int pos, j, i;
    int n=7;
    int temp;
    for (pos =0; pos < 7; pos ++){
        printf("\nPosition=%i Value=%i", pos, a[pos]);
    }
    for(i=1;i<=n-1;i++){
        temp=a[i];
        j=i-1;
        while((temp<a[j])&&(j>=0)) // while selected # less than a[j] and not j isn't 0
        {
            a[j+1]=a[j];    //moves element forward
            j=j-1;
        }
         a[j+1]=temp;    //insert element in proper place
    }

    printf("\nSorted list is as follows:\n");
    for(i=0;i<n;i++)
    {
        printf("%d\n",a[i]);
    }
    printf("\nmedian = %d\n", a[3]);
    sub_one(&a);

    return 0;
}

I need to read up on how to encapsulate pointers because that threw me off.

我需要阅读如何封装指针,因为这让我很失望。

回答by Jay Gupta

The argument of func is accepting double-pointer variable. Hope this helps...

func 的参数是接受双指针变量。希望这可以帮助...

#include <stdio.h>

int func(int **B){

}

int main(void){

    int *B[10];

    func(B);

    return 0;
}

回答by Vaibhav Balkrishna Dhole

main()
{
    int *arr[5];
    int i=31, j=5, k=19, l=71, m;

    arr[0]=&i;
    arr[1]=&j;
    arr[2]=&k;
    arr[3]=&l;
    arr[4]=&m;

    for(m=0; m<=4; m++)
    {
        printf("%d",*(arr[m]));
    }
    return 0;
}

回答by utpal podder

In the function declaration you have to type as

在函数声明中,您必须键入

VOID FUN(INT *a[]);
/*HERE YOU CAN TAKE ANY FUNCTION RETURN TYPE HERE I CAN TAKE VOID AS THE FUNCTION RETURN  TYPE FOR THE FUNCTION FUN*/
//IN THE FUNCTION HEADER WE CAN WRITE AS FOLLOWS
void fun(int *a[])
//in the function body we can use as
a[i]=var