Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes more sense - char* string or char *string? [duplicate]

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?

like image 977
Skilldrick Avatar asked Feb 17 '09 19:02

Skilldrick


People also ask

Is char * Same as string?

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.

Should I use std::string or * char?

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.

Which is faster char array or string?

So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.

Should I use string or char C++?

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.


1 Answers

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.

like image 131
Greg Hewgill Avatar answered Oct 03 '22 06:10

Greg Hewgill