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

后端 未结 5 926
孤独总比滥情好
孤独总比滥情好 2021-01-03 11:44

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


        
5条回答
  •  孤城傲影
    2021-01-03 12:13

    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.

提交回复
热议问题