How to delete a string data type?

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
*str = This is the string var ///Why does only this one stay the same
Because dereferencing a deleted pointer has undefined behavior. That is, anything at all could happen. It could print the sentence that used to be there, a full copy of Hamlet, or demons could fly out of your nose. In this case, it just happened to print that, rather than doing anything else.

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.
I assume this is meant to read
Also, before deallocating any memory, why does the char variable, ch,
only output one letter when using the * operator as opposed to
outputting the whole sentence without using the * operator.
When you print *ch, you're printing a char. In particular, the one that's at the beginning of the string.
When you print ch, you're printing a pointer. The standard IO library is designed to understand that you don't want to print a pointer (if you try to print any other type of pointer, such as an int *, you'll get something like 0xE6C7CC5), but rather the string that the pointer points to, so it prints that instead.
Last edited on
Thanks
Topic archived. No new replies allowed.