Array allocation inside c function

I am trying to allocate and initialize an array inside a function, but I cannot get 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 is a lot of documentation on pointers there, but I did not find this particular case. Any tips on what I'm doing wrong?

+3
source share
5 answers

Instead of passing a pointer to a pointer, it might be easier for you 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 is not working is as follows:

*thing[0]

Due to operator precedence, you should use:

(*thing)[0]
+6
source

* [] , *(thing[0]). (*thing)[0].

+5

func(), *thing[n] *(thing[n]), .. *(*(thing + n)), . (*thing)[n].

+3

[] , . paranthesis: (*thing)[0] = 1;

+1

() *thing = calloc(2, sizeof(int)); thing = calloc(2, sizeof(*int)); thing, .

0

Source: https://habr.com/ru/post/1774817/


All Articles