Search code examples
javac#c++carray-difference

What array structure is in C# but not in C/C++/Java?


I'm preparing for exams and there's this question I can't find answer to. Read bunch of articles, closest I found was

Arrays in C# come in three flavors: single-dimensional, multidimensional rectangular arrays (like the C++ multidimensional arrays), and jagged arrays (arrays of arrays).

So this suggests that there's no jagged arrays in C++, but it exists in Java. Another thing is that just C# can have non-zero array lower-bound(like a[-1,3] or a[4,9]. Would it be considered different array structure?


Solution

  • C++

    • So this suggests that there's no jagged arrays in C++

    By the same reading, the block of text suggests that C++ doesn't have single dimensional arrays. This is clearly absurd!

    C++ has both... You clearly can make a int**, that is a pointer to a pointer (so an "array" of pointers, so an "array" of "arrays"), like in C# you can have a int[][], that is an array of int[]. For C++ see various examples here. Note that this syntax is more C than C++... In C++ you should use std::array, like here.

    • Another thing is that just C# can have non-zero array lower-bound(like a[-1,3] or a[4,9])

    This doesn't exist in C++... They are internally implemented in C# by the same code that implements multi dimensional arrays, and exist for historical reasons (pseudo-compatibility with old versions of VB)

    Java

    Java doesn't have multi-dimensional arrays (see here). It does have jagged arrays, with a trick: if you want you can initialize a jagged array that has all the elements of the same size in a single command or if they have different sizes/some of them can be null, you can initialize them manually.

    int[][] num = new int[4][2];
    

    vs

    int[][] num = new int[4][];
    num[0] = new int[1];
    num[1] = new int[2];
    num[2] = new int[3];
    num[3] = new int[4];
    

    So in the end

                                C#    Java  C++   
    single-dimensional array    x     x     x
    multi-dimensional array     x           x
    si.di. non-zero based array x
    mu.di. non-zero based array x
    jagged array                x     x     x