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

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

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

提交回复
热议问题