So I allocate new memory for a char, int, and string variable,
initialize each one, and output each to the screen. Afterwards,
I deallocate each of them and output them again to see if they
would output the previous values. The int and char values were
deleted properly but the string was not and I used the delete
variable for each three the same.
For example....before deleting each variable...
*p = 25
ch = This is the char var
*str = This is the string var |
after deleting each variable...
*p = 4073560
ch = -
*str = This is the string var ///Why does only this one stay the same |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
int *p;
char *ch;
string *str;
p = new int;
ch = new char[256];
str = new string;
*p = 25;
strcpy(ch, "This is the char var");
*str = "This is the string var";
cout<<*p<<endl;
cout<<ch<<endl;
cout<<*str<<endl;
delete p;
delete []ch;
delete str;
cout<<endl<<endl;
cout<<*p<<endl;
cout<<ch<<endl;
cout<<*str<<endl;
return 0;
}
|
Also,
before deallocating any memory, why does the char variable,
ch,
only output one letter without using the * operator as opposed to
outputting the whole sentence when using the * operator. That is
why I outputted the
ch variable on line 22 without the * operator.
Thanks for any response