简体   繁体   中英

Passing pointer array to function in C

I am having trouble passing a pointer array to a function. I will post a simple example that still doesn't work for me. Could you please tell me what I am doing wrong?

#include <stdio.h>
#include <stdlib.h>
int transformare(int *v[1])
{
    *v[1] = 10;
    return 0;
}
int main()
{
    int v[1];
    printf("n = ");
    scanf("%d", &v[1]);
    transformare(&v);
    printf("%d", v[1]);
    return 0;
}

You have two problems:

  1. Array indexes are zero-based. That is, an array of N elements have indexes from 0 to N - 1 (inclusive)

  2. The declaration int *v[1] declares v as an array of one pointer to int , not as a pointer to an array of one int . That would be int (*v)[1] . Which is also the type of &v from the main function.

The solution to the second problem (using the correct type) then leads to a third problem, as it means that *v[0] is incorrect due to operator precedence . You need to use parentheses here too, as in (*v)[0] .


However the second (and the following third) problem is moot, since you don't need to pass arrays "by reference".

Arrays naturally decays to pointers to their first element. When using plain v when a pointer to int is expected, the compiler will automatically translate it as &v[0] .

That means you could declare the function to simply take an int * as argument, and simply pass plain v as the argument.

First, please note that indizes are 0 -based in C, ie the first (and - in your case only) element is v[0] .

Concerning passing it, just define the parameter as pointer to int, ie int* . A variable of type int[1] will decay to a pointer to int when passed to a function (so there is no need to write transformare(&v) , its transformare(v) .

int transformare(int *v)
{
    v[0] = 10;
    return 0;
}

int main()
{
    int v[1];
    printf("n = ");
    scanf("%d", &v[0]);
    transformare(v);
    printf("%d", v[0]);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM