Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete char * in c++?

Tags:

c++

In my application, I create a char* like this:

class sample
{
    public:
        char *thread;
};

sample::sample()
{
    thread = new char[10];
}

sample::~sample()
{
    delete []thread;
}

Am I doing the right thing in the code?

like image 885
karthik Avatar asked Mar 30 '11 03:03

karthik


People also ask

What does char * mean in C?

In C, char* means a pointer to a character. Strings are an array of characters eliminated by the null character in C.

Is char * A string in C?

This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.

What is a char * array in C?

In C, an array of type char is used to represent a character string, the end of which is marked by a byte set to 0 (also known as a NUL character)

Why is a char * a string?

char *A is a character pointer. it's another way of initializing an array of characters, which is what a string is. char A, on the other hand, is a single char. it can't be more than one char.


2 Answers

If you have [] after your new, you need [] after your delete. Your code looks correct.

like image 144
Fred Larson Avatar answered Oct 25 '22 21:10

Fred Larson


List of points to be noted:

1) You need to allocate room for n characters, where n is the number of characters in the string, plus the room for the trailing null byte.

2) You then changed the thread to point to a different string. So you have to use delete[] function for the variable you are created using new[].

But why are you fooling around with new and delete for character data? Why not just use std::string, instead of 'C' functions? It's amazing why so many don't do the easiest thing:

#include <cstdio>
#include <string>

int countWords(const char *p);

int main(int argc, char *argv[])
{
    std::string pString = "The Quick Brown Fox!";

    int numWords1 = countWords(pString.c_str());
    printf("\n\n%d words are in the string %s", numWords1, pString.c_str());

    int numWords2 = countWords(argv[1]);
    printf("\n%d words are in the string %s", numWords2, argv[1]);
}

No need for new[], delete[], strcpy(), etc.

Use strlen(). Better yet, don't use char* and use std::string for string data.

like image 22
karthik Avatar answered Oct 25 '22 21:10

karthik