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?
In C, char* means a pointer to a character. Strings are an array of characters eliminated by the null character 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.
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)
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.
If you have [] after your new, you need [] after your delete. Your code looks correct.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With