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() {
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.