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() {
(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;
}
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.
You'll want to use a calloc
call instead of malloc
(See this: http://www.manpagez.com/man/3/calloc/)
Instead of malloc()
ing a single int, malloc
the array.
int f1(int * b) {
b = malloc(ARRAY_LENGTH * sizeof(int));
*b = 5;
b[1] = 6;
*(b + 2) = 7;
}
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;
}