I want to initialize an array and then initialize a pointer to that array.
int *pointer;
pointer = new int[4] = {3,4,2,6};
delete[] pointer;
pointer = new int[4] = {2,7,3,8};
delete[] pointer;
How can I do this?
I want to initialize an array and then initialize a pointer to that array.
int *pointer;
pointer = new int[4] = {3,4,2,6};
delete[] pointer;
pointer = new int[4] = {2,7,3,8};
delete[] pointer;
How can I do this?
Why not use
int array[4] = {3, 4, 2, 6};
Is there a reason you want to allocate memory for the array from heap?
Suggestion after comment:
int arrays[32][4] = {{3, 4, 2, 6}, {3, 4, 1, 2}, ...} int *pointers[4]; pointers[0] = arrays[0]; pointers[1] = arrays[12]; pointers[2] = arrays[25]; pointers[3] = arrays[13]; ... pointers[0] = arrays[13]; pointers[1] = arrays[11]; pointers[2] = arrays[21]; pointers[3] = arrays[6];
int *pointer = new int[4]{3,4,2,6};
EDIT: As pointed out in the comments, this is C++0x syntax. To do this in earlier versions, write a function that takes a stack array + size, allocates a new array on the heap, loops through the stack array populating the heap array, and then returning a pointer to the heap array.
int* foo( const int size, int *array )
{
int *newArray = new int[size];
for( int index = 0; index < size; ++index )
{
newArray[index] = array[index];
}
return newArray;
}
The call would look like this:
int a[] = { 1, 2, 3, 4 };
int *ptr = foo( 4, a );
It takes two lines, but it at least is easier than initializing line by line.
//initialize the array
int array[] = {3,4,2,6};
// initialize a pointer to that array
int *pointer = array;
As others have pointed out, you can initialize non heap arrays, e.g.:
static const int ar1[4] = { ... };
static const int ar2[4] = { ... };
Then initialize your dynamically allocated array from the static data:
void func()
{
int *pointer = new int[4];
...
memcpy(pointer, ar1, sizeof(ar1));
...
memcpy(pointer, ar2, sizeof(ar2));
...
You can do something like this with a standard container and boost::assign.
std::vector vect = list_of(3)(4)(2)(6);
...
vect = list_of(2)(7)(3)(8);