interesting pointer cast problem

G

Gerald

There are several ways to build 2D array in C++.
Usually I do it using following code:

// ========================================
int rows = 10, columns = 10;
int *array1d = new int[rows*columns];
int (*array2d)[columns] = reinterpret_cast<int (*)[columns]>(array1d);
/* Now we can use array2d like this - array2d[j] */
// ========================================

The key statement is
int (*array2d)[columns] = reinterpret_cast<int (*)
[columns]>(array1d).
I wonder whether it complies with C++ spec and how it is supposed to
work.

Thanks
Gerald
 
I

Ian Collins

There are several ways to build 2D array in C++.
Usually I do it using following code:

// ========================================
int rows = 10, columns = 10;
int *array1d = new int[rows*columns];
int (*array2d)[columns] = reinterpret_cast<int (*)[columns]>(array1d);
/* Now we can use array2d like this - array2d[j] */
// ========================================

The key statement is
int (*array2d)[columns] = reinterpret_cast<int (*)
[columns]>(array1d).
I wonder whether it complies with C++ spec and how it is supposed to
work.


No, an array type requires a constant size (columns isn't).

Why don't you use a vector of vectors?
 
I

Ian Collins

Because it's slower to instantiate and consumes more memory than a one
single array used as a two-dimensional one?

But vectors are also safer and scale better. If the size is small, the
extra memory overhead probably doesn't matter. If the size is large,
the extra memory overhead is insignificant.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top