Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - malloc array in function and then access array from outside

Tags:

c

Here is how I malloc an int var and then access this var outside of the function

int f1(int ** b) {
  *b = malloc(sizeof(int)); 
  **b = 5;
}

int main() {
  int * a;
  f1(&a);
  printf("%d\n", *a);
  // keep it clean : 
  free(a);
  return 0;
}

Using same logic above, how do I malloc a 1 dim array inside a function and then access it outside of the func?

Please help, I am bit confused with pointers to array.

like image 240
ihtus Avatar asked Dec 08 '11 21:12

ihtus


3 Answers

In exactly the same way but with some different arithmetic. You can think of what you are doing now as allocating an array with one element. Just multiply sizeof(int) by the number of elements you want your array to have:

int f1(int ** b, int arrsize) {
  *b = malloc(sizeof(int) * arrsize);

  // then to assign items:
  (*b)[0] = 0;
  (*b)[1] = 1;
  // etc, or you can do it in a loop
}

int main() {
  int * a, i;
  int size = 20;

  f1(&a, size); // array of 20 ints

  for (i = 0; i < size; ++i)
      printf("%d\n", a[i]); // a[i] is the same as *(a + i)
                            // so a[0] is the same as *a

  // keep it clean : 
  free(a);

  return 0;
}
like image 106
Seth Carnegie Avatar answered Nov 15 '22 04:11

Seth Carnegie


(untested, but I believe it'll work)

int f1(int ** b) {
  *b = malloc(sizeof(int)*4); 

  (*b)[0] = 5;
  (*b)[1] = 6;
  (*b)[2] = 7;
  (*b)[3] = 8;
}

int main() {
  int * a;
  f1(&a);
  printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]); // should be "5 6 7 8"
  // keep it clean : 
  free(a);
  return 0;
}
like image 28
abelenky Avatar answered Nov 15 '22 05:11

abelenky


You are almost there *b = malloc(sizeof(int)); allocates space for a single int ( a bit pointless since the pointer is at least as big as this)

The more normal usage is *b = malloc(number_of_ints*sizeof(int));

Remember that the [] syntax just does the array maths for you (a+10) and a[10] point to exactly the same thing memory location, so you can allocate it using malloc, pass the poitner and refer to it as an array.

The only things about arrays and pointers that is complicated (apart from remembering when to use * and &) is that malloc() works in bytes, so you need to tell it the sizeof an int. But the int * it returns knows about ints so to get to the next value you only need to do a++ or a+1 or a[1] even though it is really 4 or 8 bytes different in value.

like image 36
Martin Beckett Avatar answered Nov 15 '22 05:11

Martin Beckett