i am doing a problem . take character dynamic of size 10.when user enter 11th element.it increment the array size to 20. when user enters 21st element array size increases to 30 and so on

int main(){
char *p;
p=new char [];
int size;

for(int i=0 ;i<10; ++)

i only manage to do this .i m a new in programming. please help to complete this code

Please learn how to use code tags when posting code to this board. It is a bit of a hassle, but given it preserves the spacing you (should be) use in writing the code it is well worth it. There are multiple locations on the board where you can learn how to do it. See the announcements list at the top of this board, click/hover over the word code at the top to of the Message box where you enter the text of your code, or even the watermark message within the Message box.


p=new char [];

should be this:

int capacity = 10;
p=new char [capacity];

to declare an array of capacity 10 using dynamic memory. Remember that someplace in your code you should be releasing the memory you just requested in writing that line!

To keep track of how many elements the user has entered you should be using a counter variable.

To expand the array when the counter exceeds the capacity of the array you should be using a variable called capacity to keep track of that value, too.

To repeatedly expand the array you should probably wrap the protocol to expand the array in a function and call it when needed, passing it the array to expand and a reference to current capacity of the array.

Within the function declare a new array of current capacity. Copy contents of current array into the new array. Increase capacity by 10. Release the memory in the original array. Declare new memory for the enlarged array. Copy the memory from the new array back to the enlarged array. Release the memory from the new array. Note: it's been a while since I've done this, since I usually use STL vectors to do all of this behind the scenes so I forget if the current array should be sent to the function by reference (since the memory address of the first element of the array will change in the function) or not.

Very patient reply... :)

Use vectors if you could, if not then something like this will work :
Although its not tested, its the general idea.

int base= 10;
int  * Array = new int[base];
bool end = flase;
int i = 0;

    cout <<" Enter a number : " ;
    int append = 0;
    cin >> append;
    Array[i] = append;
   if( i >=  base - 1) //check if I is at its end index
            base += 10;
          int * tmp = new int[base];
          //copy Array into tmp;
          delete [] Array;
          Array = new int [base];
          //copy tmp into Array
         //delete tmp;
  cout << " Continue <1 = yes, 0 = No > ;
  cin >> end;
This article has been dead for over six months. Start a new discussion instead.