Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between multidimensional array in java and c++? [closed]

Tags:

java

c++

char a[][4] = {{'a','a','a'},
               {'a','a','a'},
               {'a','a','a'},
               {'a','a','a'}};

In c++ you must initialize the last index of an array.

In java if you do this it will result in an error.

Can someone explain me why??

Also when I check the length of array like this in java.

System.out.println(a[0].length);

the result is the length of the column in the array

lets says there is an '\0' at the end of array and when I check the length of array in c++ like this.

cout << strlen(a[0]) 

I get the length of an entire array.

Can I just get the lenght of the row or column in an array in c++ like in java?

Is this becuase array in java is an object?

like image 768
user1394801 Avatar asked Dec 16 '22 00:12

user1394801


1 Answers

In Java, a multidimensional array is an array that contains arrays (and a multidimensional array variable does not necessarily contain a multidimensional array, i.e. it could be null). In C++, a multidimensional array variable is itself a single gigantic array, created instantly, with its multidimensional nature only being syntactic sugar. In C++, you have to initialize all but the first index of an array in order to tell the compiler how to convert between your multidimensional array syntax and the single gigantic array that it is actually using behind the scenes.

You can get more Java-like behavior in C++ by initializing a multidimensional array as a pointer to an array of pointers to arrays, instead of simply as an array of arrays (objects in Java are mostly equivalent to pointers to objects in C++). Of course, then you'd have to worry about memory management, which Java does for you.

like image 110
Brilliand Avatar answered Apr 26 '23 14:04

Brilliand