On Feb 16, 10:45 am, "whitehatmira...@gmail.com"
<whitehatmira...@gmail.com> wrote:
> Hi all
>
> Im not quite sure how to use the new and delete for a whole array
> dynamically.
> Actually i want that, a user inputs a char in a single char array.
> Everytime he inputs a char he creates a new array of (previous size +
> 1), he then copies the content of the old array in to the new array
> and adds the new input at the end and deletes the old array. I guess
> he has to pass the pointer to the array everytime.
First of all, any good reason not to use std::vector? It gives you
everything you need and saves you the hassle of allocating/
deallocating memory.
> i guess the code gotta be somthing like this:
>
> int counter = 0;
>
> int main(){
> clrscr();
> cout<<"Input a character: ";
> get_char();
> getch();
> return 0;
>
> }
>
> get_char(){
> ch = getch();
> counter ++;
> while (ch != -1){ ///exit if usr inputs -1
Allocate the new array here.
> for (int i = 0; i<counter; i++)
> dyn_array[i] = old_array[i];
>
> dyn_array[i+1] = ch;
No, 'i' is no longer in scope and this should not compile, but on
the other hand you know the size of the array and indexing to the last
element should be no problem.
> delete[] old_array;
> print_array(*ptr_to_dyn_array, counter)
ch = getch();
> }
>
> print_array(*ptr, int){
> for (int i = 0; i =<counter;i++){
std::cout << ptr[i] << " ";
> }
>
> }
--
Erik Wikström
|