help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Help: How to do a proper dynamic C++ array, new 3.4.2 compile errors


From: Jason Kraftcheck
Subject: Re: Help: How to do a proper dynamic C++ array, new 3.4.2 compile errors
Date: Tue, 22 Mar 2005 12:45:31 -0600
User-agent: Debian Thunderbird 1.0 (X11/20050116)

Eric wrote:
> I get the error "an array reference cannot appear in a constant-expression"
> when compiling the following line of code:  int (*debug)[dims[2]][dims[3]] =
> new int[dims[1]][dims[2]][dims[3]];
> 
> This code compiled and worked fine previous to GCC 3.4.2.  Am I
> approaching this the wrong way?  I am trying to create a dynamically
> sized array accessible by "some_array [x] [y] [z] =.... "
> Maybe I can change some compiler settings?  I would try 3.4.3, but mingw
> doesn't appear to have it ready for windows yet.
> 

You are relying on a gcc extension that has apparently been removed.
The above code is not portable.  Further, if you're going to rely on
that particular gcc extension, you might as well just do:
  int debug[dims[1]][dims[2]][dims[3]];

To allocate a multi-dimensional array the way you are trying to do it
(without relying on gcc-specific exntsions), all dimensions but the
first must be specified as constants.  The following should compile fine:
  int (*debug)[5][6] = new int[dims[1]][5][6];

If those dimensions are not constants, you cannot allocate the array
this way.

> I've seen some good examples of 3d arrays using vectors, but at some point I
> have to pass an array into FFTW to caculate the fourier transform.  I could 
> just
> convert it to 1D, but I am curious about this.
> 

If you need the array as a single block of memory to pass to some other
code expecting it in that format, then you'll need to do something like
the following (I may have the order of the indexing incorrect):

 // Allocate the actual storage for the array data as a
 // 1-D array to be passed to other code that expects
 // it in that format.
int debug_mem = new int[dims[1]*dims[2]*dims[3]];
 // Construct a vector named "debug" that can be used to
 // index into the above array as if it were a 3-D array.
 // (e.g. debug[0][0][0] = 1;)
std::vector<std::vector<int*>> debug(dims[1]);
int* debug_mem_iter = debug_mem;
for (std::vector<std::vector<int*>>::iterator iter1 = debug.begin();
     iter1 != debug.end(); ++iter)
{
  iter1->resize(dims[2]);
  for (std::vector<int*>::iterator iter2 = iter1->begin();
       iter2 != iter1->end(); ++iter2)
  {
    *iter2 = debug_mem_iter;
    debug_mem_iter += dims[3];
  }
}


reply via email to

[Prev in Thread] Current Thread [Next in Thread]