I am trying to create a 2d array in my program that can hold CStrings. I need to be able to add my CString to any row and column in the array(not just at the end) and I need it to be able to grow in size. Does anyone know how I could do this?

Let me explain in more detail, I have:
int numData;
CStringArray MyArray[50];

I want to be able to set the value of any element like this:

MyArray[rownumber].SetAtGrow(colnumber, value);

Is there any way at the beginning I can set it to size numData like below?

CStringArray MyArray[numData]
//this gives me an error

C++ arrays are static in size, yes, but the Standard Template Library has containers that can do what you want. lists sounds like they may fit your needs, but vectors or deques may also be of use.

As far as this:

CStringArray MyArray[numData]

You need to use dynamic memory to allocate an array to a size unknown at compile-time. Like this:

CStringArray* MyArray;
MyArray = new CStringArray[numData];
//use the array
delete[] MyArray;

If this is all you need, you can ignore the stuff about the STL (standard template library). But if you want it to grow and shrink during runtime, you'll need a list or another container.

You can declare an array of type T using static memory like so:

T myArray[constInt];

where constInt resolves to an int that is declared const, meaning its value must be known at compile time and cannot be changed at run time. If you don't know what value you want/need for constInt at compile time, then you should declare the array on the heap, using dynamic rather than static memory. That is, you can do this:

int size;
cout << "enter value for size" << endl;
cin >> size;

T myArr * = new T;

Technically myArray and myArr aren't the same thing, but they behave the same and can be used interchangably, at least for most intents and purposes. If you don't want to monkey with memory handling yourself then using something like std::vector, which is a class that acts like a souped up array with [] operator and everything including memory handling.

CString is MSs string class that acts very much like std::string, if I'm not mistaken. Since the length of any given CString may vary I don't know whether you can do this:

CString myArray[10];

You can try it and see. Likewise you can try the dynamic declaration and see if that works, too. Otherwise, a vector of CStrings should work fine.

This article has been dead for over six months. Start a new discussion instead.