Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I dimension a string at run-time?

Status
Not open for further replies.

Vdcss

Programmer
Dec 5, 2001
2
RO
How do I make this piece of code work? I have the dimension of the string at run-time...

void Sub1(int Count) {
char nrstr[Count];
.
.
.
}

or
{
int k;
k = f1();
char nrstr[k];
}

If your answer is dynamic allocation, how do I do that (define vars; add, remove items)?
 
#include <iostream>

void Sub1( int iElems );

int main()
{
Sub1( 100 );
return 0;
}

void Sub1( int iElems )
{
char *cTemp = new char[ iElems ];

for ( int i=0;i<iElems;i++ )
cTemp = '#';
for ( int x=0;x<iElems;x++ )
std::cout << &quot;Elem &quot;
<< x << &quot;: &quot;
<< cTemp[x] <<
std::endl;

delete [] cTemp;
}

As far as &quot;adding and removing&quot; elements from the dynamic array, this cannot be done. Once you allocate space from the heap to accomadate the size of your array, your pretty much stuck with it until you delete [] it. The flexability you are looking for can be found in a linked list data structure. Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top