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

后端 未结 5 1018
孤独总比滥情好
孤独总比滥情好 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:26

    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;
    }
    

提交回复
热议问题