我基本上想要相当于C的C(好吧,只是数组的部分,我不需要类和字符串解析以及所有这些):
public class Example { static int[] foo; public static void main(String[] args) { int size = Integer.parseInt(args[0]); foo = new int[size]; // This part } }
请原谅我的无知.我被java损坏了;)
/* We include the following to get the prototypes for: * malloc -- allocates memory on the freestore * free -- releases memory allocated via above * atoi -- convert a C-style string to an integer * strtoul -- is strongly suggested though as a replacement */ #includestatic int *foo; int main(int argc, char *argv[]) { size_t size = atoi(argv[ 1 ]); /*argv[ 0 ] is the executable's name */ foo = malloc(size * sizeof *foo); /* create an array of size `size` */ if (foo) { /* allocation succeeded */ /* do something with foo */ free(foo); /* release the memory */ } return 0; }
警告:关闭袖口,没有任何错误检查.
在C中,如果忽略错误检查,则可以使用此方法:
#includestatic int *foo; int main(int argc, char **argv) { int size = atoi(argv[1]); foo = malloc(size * sizeof(*foo)); ... }
如果您不想使用全局变量并且使用的是C99,则可以执行以下操作:
int main(int argc, char **argv) { int size = atoi(argv[1]); int foo[size]; ... }
这使用VLA - 可变长度数组.