I have recently started programming in C, coming from Java and Python. Now, in my book I have noticed that to make a "Hello World" program, the syntax is something like this:
char message[10]
strcpy(message, "Hello, world!")
printf("%s\n", message);
Now, this example is using a char array and I wondered - what happened to strings? Why can't I simply use one of those? Maybe there is a different way to do this?
First, you don't need to do all that. In particular, the
strcpy
is redundant - you don't need to copy a string just toprintf
it. Yourmessage
can be defined with that string in place.Second, you've not allowed enough space for that "Hello, World!" string (
message
needs to be at least 14 characters, allowing the extra one for the null terminator).On the why, though, it's history. In assembler, there are no strings, only bytes, words etc. Pascal had strings, but there were problems with static typing because of that -
string[20]
was a different type thatstring[40]
. There were languages even in the early days that avoided this issue, but that caused indirection and dynamic allocation overheads which were much more of an efficiency problem back then.C simply chose to avoid the overheads and stay very low level. Strings are character arrays. Arrays are very closely related to pointers that point to their first item. When array types "decay" to pointer types, the buffer-size information is lost from the static type, so you don't get the old Pascal string issues.
In C++, there's the
std::string
class which avoids a lot of these issues - and has the dynamic allocation overheads, but these days we usually don't care about that. And in any case,std::string
is a library class - there's C-style character-array handling underneath.There is no
string
type inC
. You have to use char arrays.By the way your code will not work ,because the size of the array should allow for the whole array to fit in plus one additional zero terminating character.
C does not have its own String data type like Java.
Only we can declare String datatype in C using character array or character pointer For example :
But you need to declare at least:
to copy "Hello, world!" into message variable.
C does not support a first class string type.
C++ has std::string
In C, a string simply is an array of characters, ending with a null byte. So a
char*
is often pronounced "string", when you're reading C code.To note it in the languages you mentioned:
Java:
Python:
Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable.
C:
or
A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator
'\0'
). Note that the sentinel character is auto-magically appended for you in the cases above.