3

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 ?

1
  • 2
    maybe there's a problem due to operator precedence? I'd try replacing all the "*thing[x]" with "(*thing)[x]". Commented Nov 14, 2010 at 19:43

5 Answers 5

6

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]
Sign up to request clarification or add additional context in comments.

Comments

5

The precedence of * and [] are such that your assignments mean *(thing[0]). You need to explicitly parenthesize like (*thing)[0].

Comments

3

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].

Comments

1

The [] has higher precedence than derefferensing. Use explicit paranthesis : (*thing)[0] = 1;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.