Reputation: 1211
I'm trying to allocate and initialize an array inside a function, but I can't seem to fetch the values after returning.
This was my last almost-working attempt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int func(int **thing);
int main() {
int *thing;
func(&thing);
printf("%d %d", thing[0], thing[1]);
}
int func(int **thing) {
*thing = calloc(2, sizeof(int));
*thing[0] = 1;
*thing[1] = 2;
printf("func - %d %d \n", *thing[0], *thing[1]);
}
but the values printed outside the function are 1 and 0. There are lots of documentation on pointers out there, but I haven't found this specific case covered. Any tips on what I'm doing wrong ?
Upvotes: 3
Views: 2512
Reputation: 28693
After using ()
for the right precedence, do not forget to change *thing = calloc(2, sizeof(int));
to thing = calloc(2, sizeof(*int));
and to allocate memory for thing
elements, since its elements are pointers to integers.
Upvotes: 0
Reputation: 14870
The []
has higher precedence than derefferensing. Use explicit paranthesis : (*thing)[0] = 1;
Upvotes: 1
Reputation: 272467
Inside func()
, *thing[n]
is equivalent to *(thing[n])
, i.e. *(*(thing + n))
, i.e. array indexing takes precedence over dereferencing. You need to assign using (*thing)[n]
.
Upvotes: 3
Reputation: 93700
The precedence of *
and []
are such that your assignments mean *(thing[0])
. You need to explicitly parenthesize like (*thing)[0]
.
Upvotes: 5
Reputation: 992877
Rather than passing a pointer-to-pointer, you may find it easier to return the newly allocated array from your function:
int *func();
int main() {
int *thing;
thing = func();
printf("%d %d", thing[0], thing[1]);
}
int *func() {
int *thing;
thing = calloc(2, sizeof(int));
thing[0] = 1;
thing[1] = 2;
printf("func - %d %d \n", thing[0], thing[1]);
return thing;
}
The reason your code doesn't work is because of this:
*thing[0]
Due to the precedence of operators, you should use:
(*thing)[0]
Upvotes: 6