tags:

views:

150

answers:

7

int java declaration of array like this int a[][]=new int[3][3] works but in c++ not why? please help me i have not used c++ a long time so please help me

+7  A: 

In C++ you would just say int a[3][3];. C++ doesn't require all arrays and objects to be declared with new.

EDIT: For a dynamic size n you can't use stack based arrays.

Probably the best way is a vector of vectors:

std::vector<std::vector<int> > a;
a.resize(n);
for(int i = 0; i < n; ++i)
{
    a[i].resize(n);
}
Mark B
yes i know but for example we dont want use number but variable let say n can we declare it as a[n][n[?
then n must be a const int.
tlayton
@davit-datuashvili What you are looking for are called "variable length arrays". These are permitted in C99, but not in C89 or C++. Some compilers support these as an extension in C++, but they are not standard. In C++, you would normally use `std::vector` for this sort of thing.
Tyler McHenry
A: 

In C++ you can declare a 2-dimensional int-array of a predetermined size using int a[30][10];.

You can allocate new arrays with new in Java because arrays are Objects ant thus they have to be created using new in Java. But C++ does not force you to create everything using new.

Of course, it would be no problem to introduce these new syntax for declaring arrays also in C++, but why introduce a new syntax, if "everybody" is used to the existing one?

Note that you can not declare a 2-dimensional array with sizes determined at runtime using int arr[n][m]. You have to create an array of arrays representing a 2-dimensional array using int **arr = new int[n][m] i.e. in C++ an array of pointers pointing to each subarray. Analoguesly for higher dimensional arrays.

Another way for multidimensional arrays is to declare just a 1-dimensional array and compute the indices accordingly. However, this involves some thoughts on how to organize data.

phimuemue
A: 

This topic deals with two important aspects of C++: explicit pointers and dynamic memory. The short answer is that, in C++, all two need to do to initialize an array is declare it, like so:

int a [5][5];

If you want to use a variable for the array size, it must be a const int:

const int n = 5;
int b [n];

Be aware, however, that much of the functionality of arrays in Java does not exist in C++. For example, there is no straightforward "length" attribute.

The long answer is, look up the two topics addressed above, in particular in terms of arrays and the "new" keyword, as well as the "const" keyword. Understanding these ideas is vital to using C++;

tlayton
+2  A: 

In C++ you can allocate arrays on the stack or on the heap. Allocation on stack is only possible for fixed-size arrays (i.e. the sizes are known at compile time):

int a[3][3];

The above allocates a 3x3 array on the stack. If you want to dynamically allocate arrays (i.e. the size is not know at compile time), it has to be done on the heap. To my knowledge however, C++ does not directly support multydimensional arrays. So you may have to do something like

int * a = new int[n*n];

And then access an element at (i,j) as a[i + j * n].

Alternatively you can also something like

int **a = new *int[n];
for(int i = 0; i < n; ++i {
  a[i] = new int[n];
}

Trying to allocate a dynamic array on the stack such as

int a[n][n];

Will result in a compiler error.

inflagranti
You can't allocate multidimensional arrays with a single new expression like that.
Mike Seymour
Yeah, I just realized it myself. Changed the code.
inflagranti
+5  A: 

Generally speaking, you should avoid using arrays in C++ at all. While there are special cases where they're (nearly) the only choice, your first choice should generally be to use a std::vector instead. In this case, what you want becomes fairly straightforward:

// vector of 3 ints, each initialized to 0
std::vector<int> init(3, 0);   

// vector of three vectors of int, each initialized to the value of 'init':
std::vector<std::vector<int> > a(3, init);
Jerry Coffin
why should we avoid using array in C++?
Ankiov Spetsnaz
@Ankiov: Because in most cases, people require resizable arrays. And even if they don't, using a `std::vector` allows you to use iterators. And each time you avoid using an iterator, god kills a kitten.
ereOn
Exception safety, for one. If you want a variable length array in standard C++, your only option is to allocate it on the heap. But good RAII practice is to wrap all heap allocations in objects so that they don't leak memory on exceptions. `std::vector` is such a wrapper (among other features that it provides).
Tyler McHenry
@ereOn Although I would, like you, suggest avoiding arrays, a pointer into an array can be used as if it were an iterator anywhere that an iterator is required.
Tyler McHenry
It's not that you should really *avoid* using arrays, but `std::vector`s are usually much easier to use. You don't have to pass vector size together with itself every time you use it in a function, you can use iterators and, finally, memory management becomes much easier with vectors, because you don't have to keep track of as many pointers, as with arrays. It's simply a matter of minimizing possibilities of errors and bugs creeping out.
deemoowoor
keep in mind that not everybody develops in C++ for PC's....embedded system implementations don't often allow extra libraries ;)
espais
@espais: vector is part of the *standard* library, not an "extra" library. If you can't use that (directly) you'd still be best off writing most of your code to use it, and implement it yourself.
Jerry Coffin
@ereOn: I confess, I am a kitten killer.
Ankiov Spetsnaz
@Jerry - didn't realize that...i confess i've been out of the loop when it comes to vector and other libraries...good to know!
espais
A: 

The closest match is this:

int a[][] = { 
    new int[3],
    new int[3],
    new int[3]
};

with memory management being your responsibility in C++ (unless you're using a non-standard custom new[]) -- this means you will have to call delete[] for each of elements of a.

It's best to declare it this way, though:

int a[3][3];

This will create an automatic 3x3 two-dimensional array. Unlike the first example, its memory will be allocated on the stack and thus will be deleted automatically. No need to call delete on this one.

deemoowoor
A: 

I once had this same problem and ended up creating a class for it. Basically it's stored as a pointer of single dimension array and the pointers are manipulated a bit so that it acts just like a 2D array (matrix). Here's the code I used:

#include <utility>
#include <memory.h>

template <typename T>
class Matrix
{
protected:
    T** m;
    int x,y;

    __forceinline void setMatrix()
    {
        assert(x > 0);
        assert(y > 0);
        m = new T*[y];
        m[0] = new T[x*y];
        for (int i = 1; i < y; ++i)
        {
            m[i] = m[i-1] + x;
        }
    }
public:
    Matrix():m(0),x(0),y(0){}
    Matrix(int rows, int cols):x(cols),y(rows),m(0)
    {
        setMatrix();
    }

    Matrix(const Matrix<T>& mat):m(0),x(mat.x),y(mat.y)
    {
        setMatrix();
        memcpy_s(m[0], x*y, mat.m[0], x*y);
    }

    ~Matrix()
    {
        if (m)
        {
            delete[] m[0];
            delete[] m;
        }
    }

    void fill(const T& val)
    {
        if (m)
        {
            for (int j = 0; j < y; ++j)
                for (int i = 0; i < x; ++i)
                    m[j][i] = val;
        }
    }

    T& at(int row, int col)
    {
        assert(row >= 0 && row < y);
        assert(col >= 0 && col < x);
        return m[row][col];
    }

    const T& at(int row, int col) const
    {
        assert(row >= 0 && row < y);
        assert(col >= 0 && col < x);
        return m[row][col];
    }

    T* operator[](int row)
    {
        assert(row >= 0 && row < y);
        return m[row];
    }

    const T* operator[](int row) const
    {
        assert(row >= 0 && row < y);
        m[row];
    }

    T& operator ()(int row, int col)
    {
        assert(row >= 0 && row < y);
        assert(col >= 0 && col < x);
        return m[row][col];
    }

    const T& operator ()(int row, int col) const
    {
        assert(row >= 0 && row < y);
        assert(col >= 0 && col < x);
        return m[row][col];
    }

    void swap(Matrix<T>& mat)
    {
        std::swap(m, mat.m);
        std::swap(x, mat.x);
        std::swap(y, mat.y);
    }

    const Matrix& operator = (const Matrix<T>& rhs)
    {
        Matrix temp(rhs);
        swap(temp);
        return *this;
    }

    //

    int getRows() const
    {
        return y;
    }

    int getColumns() const
    {
        return x;
    }
};

Usage would be like:

typedef Matrix<int> IntMatrix;
IntMatrix mat(2,3); // Creates a 2x3 matrix to store integers.
mat.fill(0); // Fill it with zeroes.
int val02 = mat[0][2]; // Unsafe way to retrieve values
int val12 = mat(1,2); // Safe way to retrieve values;
mat(0,1) = 10; // Assign values directly to the matrix.

You can also extend this class so that it has other matrix related function in it.

Vite Falcon