I try use a integer array in java with the code below:
public static void main(String[] args) {
int[] array = testArray(100);
System.out.println(array.length);
for(int i = 0; i < 100; i++)
System.out.println(array[i]);
}
public static int[] testArray(int size){
int[] array = new int[size];
for(int i = 0; i < size; i++)
array[i] = i;
return array;
}
I also test an integer array in C++ as below:
#include<iostream>
using namespace std;
void getArray(int size)
{
int array[size];
for(int i=0; i<size; i++)
array[i]=i;
}
int main()
{
getArray(10);
return 0;
}
And I always get the right answer with the two snippets, why? since I think that the length of an array cannot be variable for language such as java, c and c++.
The three languages are different, and the features of the different languages will, well, differ. In particular, in C99 you can define arrays of a variable in the stack (for those that program mainly Java, this is commonly used to refer to a size that is not a compile time constant, not that the array will change sizes).
In C++ you cannot declare them in the stack (GCC allows this, with a non-conforming extension to the language that mimics C99 behavior), but you can dynamically allocate memory with
newof the given size and store the pointer in a variable.In Java you cannot create an array in the stack ever, and all you can do is dynamically allocate the array with
newand store a reference.