Again Dynamic memory allocation

W

whitehatmiracle

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.


For example.
input: a
output a
input: b
output: a b
input c:
output a b c .


Any clues??????????????




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

for (int i = 0; i<counter; i++)
dyn_array = old_array;


dyn_array[i+1] = ch;
delete[] old_array;
print_array(*ptr_to_dyn_array, counter)



}


print_array(*ptr, int){
for (int i = 0; i =<counter;i++){
}


}


Something like this ............!!!!!?????
Im confused.........?????????????
 
?

=?iso-8859-1?q?Erik_Wikstr=F6m?=

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 = old_array;

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 << " ";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top