I'm learning C++ at the moment, and I'm coming across a lot of null-terminated strings. This has got me thinking, what makes more sense when declaring pointers:
char* string
or
char *string
? To me, the char* format makes more sense, because the type of "string" is a pointer to a char, rather than a char. However, I generally see the latter format. This applies to references as well, obviously.
Could someone tell me if there is a logical reason for the latter format?
Before we look into java char to String program, let's get to the basic difference between them. char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars.
Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.
So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.
In C++ you should in almost all cases use std::string instead of a raw char array. std::string manages the underlying memory for you, which is by itself a good enough reason to prefer it.
In the following declaration:
char* string1, string2;
string1
is a character pointer, but string2
is a single character only. For this reason, the declaration is usually formatted like:
char *string1, string2;
which makes it slightly clearer that the *
applies to string1
but not string2
. Good practice is to avoid declaring multiple variables in one declaration, especially if some of them are pointers.
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