• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# changeing size of array

## Recommended Posts

Dwiel    365
I was writing a class that could read a file based on templates, and instances of those templates. Anyway... I was wondering if there was a way to have an array that has a variable number of elements. I know you can do it in VB, but I have been tring to do most of my programming in vc++ because, well, IT''s BETTER! Anyway if anyone knows how to do this I would be very happy if they explain it to me. thanx Tazzel3D ~ Zach

##### Share on other sites
Guest Anonymous Poster
The way to do it is that you would have a pointer to the first entry of the array of elements in your class. Which when you want to resize the array you create a new pointer to a new array that is allocated to whatever the new size of the array is, then from there you copy the data from the old size array to the new size array, then delete the old array. It might sound complicated but its actually quite simple - below i illustrate.

template

class CArray
{
public:
ResizeArray(int iNewSize, BOOL bCopyOldData){
ArrayType *pNewArray = new ArrayType[m_iNewSize];

for(int i = 0;i < iNewSize;i++)
*(pNewArray + i) = *(m_pArray + i);

delete m_pArray;
m_pArray = pNewArray;
}

SetArrayEntry(int iArrayEntryNum, ArrayType Entry)
{
*(m_pArray + iArrayEntryNum) = Entry;
}
private:
ArrayType *m_pArray;
int m_iArraySize;
};

Im pretty sure that should be a working C++ teplate dynamic array class thingy. (Plz excuze me if there were errors - havn''t worked with C++ in a while) I reccomend you make one with more functionality though. Hope I helped.

-MaNiAk

##### Share on other sites
Guest Anonymous Poster
o ya one more thing the code i gave you is rather prone to errors. Ill leave it to you to write code to check for that - if the code seems rather complex for you i reccomend reading C++ in ten minutes by Jesse Liberty. Its a real good small book and only 13 bucks.

-MaNiAk

##### Share on other sites
Guest Anonymous Poster
use a vector or a list. STL is wonderful, use it.

##### Share on other sites
Gorg    248
vector is your solution, because vectors have been designed to work and be used like a C array. Yes, yes, you can use it instead of a real array!

You can do things like that and it is valid :

  #include void fillArray( int array[], int size ){ for( int i =0; i < size; ++i ) { array[i] = i; }}int main(){ std::vector myArray; myArray.resize(10); //make vector size 10 //yes this works and is valid by standard and //supported by all flavor of STL libraries fillArray( &myArray[0], myArray.size() );}