Okay... my goal is to start with an array of for instance 5 entries.

int myArray[5];

Then at some point once the array is passed to a function, change the number of entries (example: load a new list of something into the array that has a different number of entries) to for instance 9.

int myArray[9];

Simply doing the following does not seem to work because it returns a runtime error #2 about the stack around my array getting messed with:

myArray = new int[i_Count];

Also I tried another method of creating a new array in my function, filling it, then "delete" the old array and replace it with the new. This gave me an assertion error. example:

// initial declaration
int *myArray = new int[5];

// code of whatever
...

// in function array change
int myFunct(int *a_myArray)
{
     // new array
     int a_myArray2 = new int[9];

     // random code for filling array
     ...

     // delete old and create new
     delete [] a_myArray;
     a_myArray = a_myArray2;
}

I am stumped... my goal is to "in a function change the number of entries and values of an array from within a called function, which will not only when returning to the main procedure retains the changes, but also does not cause stack errors or assertion errors."

Thanks in advance. Insights would be appreciated.

Recommended Answers

All 2 Replies

just type 'resize + array' in the search text box and you will find the answer.

>Simply doing the following does not seem to work because it returns a runtime error #2
I have no idea what your compiler thinks runtime error #2 is, but you can't assign a pointer to an array, which is precisely what you're trying to do with myArray = new int[i_Count]; . The two types are incompatible.

>This gave me an assertion error.
That's no surprise, actually. You're deleting the original memory in your function, but because the function parameter is a copy of the original pointer, you're effectively doing this:

void myFunct(int *a_myArray)
{
     // Create a memory leak
     new int[9];

     // Create a dangling pointer
     delete [] a_myArray;
}

To actually change the original pointer, you need to pass a reference to it:

void myFunct(int*& a_myArray)
{
     // new array
     int *a_myArray2 = new int[9];

     // random code for filling array
     //...

     // delete old and create new
     delete [] a_myArray;
     a_myArray = a_myArray2;
}

My recommendation is to avoid arrays and simulated arrays entirely and just use a vector object:

#include <vector>

int main()
{
  std::vector<int> v ( 5 );

  //...

  v.resize ( 9 );

  //...
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.