Why can a function return an array setup by malloc

2019-03-31 20:51发布

Why can I return from a function an array setup by malloc:

int *dog = (int*)malloc(n * sizeof(int));

but not an array setup by

 int cat[3] = {0,0,0};

The "cat[ ]" array is returned with a Warning.

Thanks all for your help

7条回答
一夜七次
2楼-- · 2019-03-31 21:49

cat[] is allocated on the stack of the function you are calling, when that stack is freed that memory is freed (when the function returns the stack should be considered freed).

If what you want to do is populate an array of int's in the calling frame pass in a pointer to an that you control from the calling frame;

void somefunction() {
  int cats[3];
  findMyCats(cats);
}

void findMyCats(int *cats) {
  cats[0] = 0;
  cats[1] = 0;
  cats[2] = 0;
}

of course this is contrived and I've hardcoded that the array length is 3 but this is what you have to do to get data from an invoked function.

A single value works because it's copied back to the calling frame;

int findACat() {
  int cat = 3;
  return cat;
}

in findACat 3 is copied from findAtCat to the calling frame since its a known quantity the compiler can do that for you. The data a pointer points to can't be copied because the compiler does not know how much to copy.

查看更多
登录 后发表回答