我正在尝试找出创建数组的方法,该数组的长度在运行时(例如,通过用户输入)在C和Java中确定。
在C中,我知道某些版本的C标准(例如C99)现在允许以下方式:
int size;
scanf("%d",&size);
int arr[size];
但是,从理论上讲,在C中创建动态数组是不可接受的。全局解决方案是在C中使用malloc()。
我的问题是,在Java中怎么样?我在自己的计算机上运行了以下Java程序,没有生成错误。但我不确定它是否仅对特定的Java平台(如C语言中的C99)是正确的,或者它在所有Java中都是普遍接受的
import java.util.Scanner;
public class Main{
public static void main(String[] args){
int size;
System.out.println("enter a number:");
Scanner s = new Scanner(System.in);
size = s.nextInt();
int[] arr = new int[size];
}
}
答案 0 :(得分:0)
这是完全可以接受的,通常用Java完成。 new int[number]
在运行时执行,动态数字执行。
只要数组的长度为非负int
,这在Java中就有效。
答案 1 :(得分:0)
在java中,您可以设置数组的长度,因为数组的创建是在运行时执行的,并且应该在所有Java平台中都可以接受。
答案 2 :(得分:0)
在Java中,数组在堆上分配。如果分配失败,则抛出可捕获的异常!可以从失败的阵列分配中恢复。
% java Main
enter a number:
1231231231
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Main.main(Main.java:12)
抓住例外:
try {
int[] arr = new int[size];
} catch (OutOfMemoryError e) {
System.out.println("Alas, such array could not be allocated. Try a smaller number next time!");
}
你得到了
% java Main
enter a number:
1231231231
Alas, such array could not be allocated. Try a smaller number next time!
在C99中简单使用可变长度数组的原因通常是不满意的是该数组是在堆栈上分配的。现在,如果数组的大小来自用户,则很容易导致无法控制的崩溃:
#include <stdio.h>
int main(void) {
int size;
scanf("%d", &size);
volatile int arr[size];
printf("%d\n", arr[size - 1]);
}
现在编译并运行:
% ./a.out
1231231231
zsh: segmentation fault (core dumped) ./a.out
无法检查分配是否成功。因此,如果您不确定 - 特别是在使用可能来自不受信任的用户的数字时,您不应该使用堆栈分配的可变长度数组。