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;
}
2 Answers 2
You have two problems:
Array indexes are zero-based. That is, an array of N elements have indexes from
0toN - 1(inclusive)The declaration
int *v[1]declaresvas an array of one pointer toint, not as a pointer to an array of oneint. That would beint (*v)[1]. Which is also the type of&vfrom themainfunction.
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.
Comments
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;
}
*v[1] = 10;accesses the array out of boundsint transformare(int *v[])orint transformare(int **v)instead.int v[1];is an array of oneint. What exactly do you want to do here?int *v[1]in the deceleration and the function deceleration of functiontransformareshould be something likeint transformare(int *v[])and while calling it, you can just calltransformare(v)