Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

char* vs char 1

Status
Not open for further replies.

szNoobProgrammer

Programmer
Jul 27, 2005
1
US
I have a question. What is the difference between declaring a null-terminated character array with
Code:
char* <name>
vs
Code:
char <name>
besides the fact that the char* prefix also can point to the first character in other, already declared, character strings? I'm just teaching myself the language, I'm a noob.
 
A char is a datatype that holds a single character. For example, a char variable could hold 'A' or '1' or '\n'. A char variable never holds more than a single character. You cannot declare a null-terminated array by simply saying char <name>, because it is only a single character.

I think you mean to ask about the difference between
Code:
char* <name>
vs
Code:
char <name>[<size>]
The first declares simply a pointer. You have to either allocate space for that pointer with new, or point it at an existing string. It is commonly used when the string length is unknown (dynamic memory with new) or to point at constant strings (e.g. char* name = "George";). The second example should really be const char* name = "George"; because you are not allowed to change the string (this is a common mistake).

The second declares a static array of the given size. This size must be a constant known at compile time in C++. If you assign a constant string to it, then you can leave out the size and the compiler will figure it out (e.g. char name[] = "George";). In this case, the compiler creates an array of 7 characters (six letters plus null terminator) and copies "George" into the array. This is different from the pointer version above, because you are allowed to modify the contents of this string. The drawback is that it holds at most 7 characters in this example.

Since you are a "noob", I highly suggest that you learn the C++ string class if you plan on learning C++. It is easier to use than C style strings (like you are asking about), it is more flexible and it is safer. In my opinion, you should save learning about pointers and arrays until you want to learn low-level details of the language later on.
 
uolj,
why
Code:
char <name>[<size>]
declares a static array of the given size?
How about
Code:
void f()
{
   char a[] = "Sorry, I\'m automatic (not static;) array!";
   ...
}
 
Thanks for the correction. I had meant an array on the stack as opposed to using dynamic memory on the heap.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top