0

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;
}
Calin Chaly
  • 59
  • 1
  • 7
  • 4
    `*v[1] = 10;` accesses the array out of bounds – UnholySheep Nov 13 '18 at 09:53
  • also, in the function declaration try `int transformare(int *v[])` or `int transformare(int **v)` instead. – Tero Niemi Nov 13 '18 at 09:55
  • 2
    [a pointer to an array is not the same as an array of pointers](https://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation) – Sander De Dycker Nov 13 '18 at 09:55
  • What "pointer array"? `int v[1];` is an array of one `int`. What exactly do you want to do here? – Lundin Nov 13 '18 at 10:02
  • Shouldn't it be `int *v[1]` in the deceleration and the function deceleration of function `transformare` should be something like `int transformare(int *v[])` and while calling it, you can just call `transformare(v)` – RishabhHardas Nov 13 '18 at 10:41

2 Answers2

2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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

Concerning passing it, just define the parameter as pointer to int, i.e. 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;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58