为什么Java函数能够返回局部数组?

huangapple go评论69阅读模式
英文:

Why are Java functions able to return local arrays?

问题

只是我注意到的一点:在C语言中,例如,如果您在函数内部有一个局部数组

*int returnArr() {
    int arr[5] = {0};
    return arr;
}

显然,这将无法编译。C语言会告诉您尝试返回局部变量。然而在Java中,同样的操作可以执行...

int[] returnArr() {
    int[] arr = new int[5];
    return arr;
}

而且这不会引起任何问题?为什么会这样?为什么Java可以做到,而C却不行?

英文:

Just something I noticed: In C, for example, if you have a local array inside a function

*int returnArr() {
    int arr[5] = {0};
    return arr;
}

Obviously this will not compile. C will tell you that you're trying to return a local variable. Yet in Java, the same can be done...

int[] returnArr() {
    int[] arr = new int[5];
    return arr;
}

and it causes no problems? Why is this? Why can Java do it but C can't?

答案1

得分: 6

你展示的两个代码片段实际上并不完全等价。在Java中,所有数组都是动态分配的(在堆上),而不是像在C中那样作为'函数局部'(在栈上)创建。

与您的Java代码最接近的C代码将是使用malloc()calloc()函数(后者包含您的= {0}初始化)。

因此,以下代码是可以的(但您需要在某个时刻'手动'使用free()来释放内存,以模拟Java中的垃圾回收器):

int *returnArr() {
    int* arr = calloc(5, sizeof(int)); // "calloc"初始化为零
    return arr;
}
英文:

The two code snippets you show aren't really equivalent. In Java, all arrays are dynamically allocated (on the heap), rather than being created as 'function local' (on the stack).

The C code most nearly equivalent to your Java code would be to use either the malloc() or calloc() function (the latter to incorporate your = {0} initialization).

Thus, the following would be fine (but you would have to 'manually' release the memory using free() at some point, to emulate the Garbage Collector that Java has):

int *returnArr() {
    int* arr = calloc(5, sizeof(int)); // "calloc" initializes to zero
    return arr;
}

huangapple
  • 本文由 发表于 2020年10月13日 00:34:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64321769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定