I mean what is the difference of string in C and C++?
C does not define string: it only has "perfectly ordinary arrays of characters" and pointers to those arrays;
C++ defines it, as a class type, with several properties and methods.
In C there is no such thing/type as "string". It is represented as NULL terminated array of characters like char str[256];. C++ has string class in standard library that internally maintains it as array of characters and has many methods and properties to manipulate it.
I fully agree with #pmg answer. But one need to mention some things. In C programmer must be very careful when he works with C-strings because a) every C-string must be ended with zero code character; b) it is very easy to make buffer overrun if buffer size for string is too small. Also in C all work with strings goes through functions. It may be programmers nightmare. In C++ things are much simpler. Firstly, you don't need to care about memory management. String class allocate additional memory when internal buffer becomes small. Secondly, you don't need to care about zero terminating character. You work with container. Thirdly, there are simple methods for working with string class. For example, overloaded operator + for string concatenation. No more awful strcat() calls. Let the work with strings to be simple!
in C++ String objects are a special type of container, specifically designed to operate with sequences of characters.string class defined in string
or in C string is a character sequence terminated with a null character ('\0'), all functions related to strings defined in string.h
Related
In C (not C++), we can think several ways of handling strings with its length:
Just rely on the null terminating character (\0): We assume that the string doesn't contain \0. Store a string to a char array and append \0 at the end. Use the functions like strlen() when we need its size.
Store the characters and the length into a struct:
typedef struct _String {
char* data;
int size;
} String;
Use another variable for storing the length: For example,
char name[] = "hello";
int name_size = 5;
some_func(name, name_size, ...);
Personally, I prefer to use the second approach, since
It can cover some 'weird' strings which contain \0 in the middle.
We may implement some functions like string_new(), string_del(), string_getitem(), etc. to write some 'OOP-like' codes.
We don't have to two (or more) variables to handle the string and its length together.
My question is: What is the most-used way to handle strings in C? (especially: when we have to use a lot of strings (ex. writing an interpreter))
Thanks.
What is the most-used way to handle strings in C?
No doubt the most common way by far is to simply rely on the null termination.
Is it the "best" way? Probably not. Using a custom string library may be the "best" way as far as execution speed and program design are concerned. The downside is that you would have to drag that library around, since there are no standard or even de facto standard string libraries for C.
Most C programmers simply use asciiz strings and accept the inefficiency. C is still a very fast language.
However if you are doing a lot of string processing, it's maybe worthwhile writing a dedicated string library or suite. So a struct with a length member and a pointer is an obvious choice. However if you get really advanced, for example for genetic data processing, you find that you need structures such as suffix trees, which allow searches for sub-strings in O(constant) time.
In C language, a string is by definition a null terminated string. That's the reason why litteral string are null terminated, and why the strxxx functions of the Standard Library operate on null terminated strings.
On the other hand, character arrays can contain what you want including nulls, and you have to pass their length in another way, like for any other array.
Because of the way C handles string litterals and of the C standard library, C programmers ordinarily use null terminated strings. But it is worth noticing that in C++ a std::string is close(*) to a character array and a length and even if it is a different language C++, the introduction of C++ standard says (emphasize mine):
C++ is a general purpose programming language based on the C programming language...
Another example is the way Windows API internally manages unicode strings as BSTR. A BSTR is a special array of uint16_t where the length is at a -1 offset. This was choosen for compatibility with Visual Basic.
So if you need it, it is perfectly fine to build a library using strings defined as a struct array + length... or use the WINAPI implementation if appropriate or migrate to C++.
(*) In fact a C++ string is a smart pointer counting references to a character array and its length
Obviously the most used way is the null-terminated way, since that is supported by the standard libraries.
Writing your own structures for strings may make sense for your purpose, but it will never become "the most used way", because it is not a standard way.
Just wondering why this is the case. I'm eager to know more about low level languages, and I'm only into the basics of C and this is already confusing me.
Do languages like PHP automatically null terminate strings as they are being interpreted and / or parsed?
From Joel's excellent article on the topic:
Remember the way strings work in C: they consist of a bunch of bytes followed by a null character, which has the value 0. This has two obvious implications:
There is no way to know where the string ends (that is, the string length) without moving through it, looking for the null character at the end.
Your string can't have any zeros in it. So you can't store an arbitrary binary blob like a JPEG picture in a C string.
Why do C strings work this way? It's because the PDP-7 microprocessor, on which UNIX and the C programming language were invented, had an ASCIZ string type. ASCIZ meant "ASCII with a Z (zero) at the end."
Is this the only way to store strings? No, in fact, it's one of the worst ways to store strings. For non-trivial programs, APIs, operating systems, class libraries, you should avoid ASCIZ strings like the plague.
Think about what memory is: a contiguous block of byte-sized units that can be filled with any bit patterns.
2a c6 90 f6
A character is simply one of those bit patterns. Its meaning as a string is determined by how you treat it. If you looked at the same part of memory, but using an integer view (or some other type), you'd get a different value.
If you have a variable which is a pointer to the start of a bunch of characters in memory, you must know when that string ends and the next piece of data (or garbage) begins.
Example
Let's look at this string in memory...
H e l l o , w o r l d ! \0
^
|
+------ Pointer to string
...we can see that the string logically ends after the ! character. If there were no \0 (or any other method to determine its end), how would we know when seeking through memory that we had finished with that string? Other languages carry the string length around with the string type to solve this.
I asked this question when my underlying knowledge of computers was limited, and this is the answer that would have helped many years ago. I hope it helps someone else too. :)
C strings are arrays of chars, and a C array is just a pointer to a memory location, which is the start location of the array. But also the length (or end) of the array must be expressed somehow; in case of strings, a null termination is used. Another alternative would be to somehow carry the length of the string alongside with the memory pointer, or to put the length in the first array location, or whatever. It's just a matter of convention.
Higher level languages like Java or PHP store the size information with the array automatically & transparently, so the user needn't worry about them.
C has no notion of strings by itself. Strings are simply arrays of chars (or wchars for unicode and such).
Due to those facts C has no way to check i.e. the length of the string as there is no "mystring->length", there is no length value set somewhere. The only way to find the end of the string is to iterate over it and check for the \0.
There are string-libraries for C which use structs like
struct string {
int length;
char *data;
};
to remove the need for the \0-termination but this is not standard C.
Languages like C++, PHP, Perl, etc have their own internal string libraries which often have a seperate length field that speeds up some string functions and remove the need for the \0.
Some other languages (like Pascal) use a string type that is called (suprisingly) Pascal String, it stores the length in the first byte of the string which is the reason why those strings are limited to a length of 255 characters.
Because in C strings are just a sequence of characters accessed viua a pointer to the first character.
There is no space in a pointer to store the length so you need some indication of where the end of the string is.
In C it was decided that this would be indicated by a null character.
In pascal, for example, the length of a string is recorded in the byte immediately preceding the pointer, hence why pascal strings have a maximum length of 255 characters.
It is a convention - one could have implemented it with another algorithm (e.g. length at the beginning of the buffer).
In a "low level" language such as assembler, it is easy to test for "NULL" efficiently: that might have ease the decision to go with NULL terminated strings as opposed of keeping track of a length counter.
They need to be null terminated so you know how long they are. And yes, they are simply arrays of char.
Higher level languages like PHP may choose to hide the null termination from you or not use it at all - they may maintain a length, for example. C doesn't do it that way because of the overhead involved. High level languages may also not implement strings as an array of char - they could (and some do) implement them as lists of arrays of char, for example.
In C strings are represented by an array of characters allocated in a contiguous block of memory and thus there must either be an indicator stating the end of the block (ie. the null character), or a way of storing the length (like Pascal strings which are prefixed by a length).
In languages like PHP,Perl,C# etc.. strings may or may not have complex data structures so you cannot assume they have a null character. As a contrived example, you could have a language that represents a string like so:
class string
{
int length;
char[] data;
}
but you only see it as a regular string with no length field, as this can be calculated by the runtime environment of the language and is only used internally by it to allocate and access memory correctly.
They are null-terminated because whole plenty of Standard Library functions expects them to be.
I am creating a Window in D, and the CreateWindowA function requires pointers to characters, C character arrays basically.
How do I convert a D style array (char[]) to a C style array (char*)?
The two functions to look at are normally std.string.toStringz and std.utf.toUTFz.
toStringz will convert string to immutable(char)*, which you can pass to a C function which takes const char*. If it can determine that the string is null-terminated (which usually is only the case for string literals, which have a null terminator one passed their end), then it won't allocate and will just use the string's ptr property, but in most cases, it will allocate.
toUTFz will convert from any string type to any character pointer type. It's probably most frequently used for converting to const(wchar)* for Windows, since all of the W functions for Windows take UTF-16, but it can also be used to convert to char* - e.g. str.toUTFz!(char*)(). Like toStringz, it will try not to allocate if it can determine that it's unnecessary, but it's almost always necessary.
Now, for your particular case, you're trying to use one of the A functions in Windows. This is almost always a bad idea, and I would strongly advise against it. Use toUTFz to convert your string to const(wchar)* and pass that to CreateWindowW. AFAIK, the only advantage to the A functions is that they work with pre-Win2K. Everything else about them is worse. However, if for some reason, you insist on using the A functions, then you're going to have to use std.windows.charset.toMBSz, because the A functions don't take UTF-8 but rather the "Windows 8-bit character set," and toMBSz will convert the string to that format.
you grab the ptr field of the D array. and the length field to grab the length
however if you need a C-style string then you need the toStringz method that will add the null terminator and return the pointer to the first char. keep a reference to it if the api doesn't create it's own copy to operate on to avoid dangling pointers by GC
I have a simple question. Why is it necessary to consider the terminating null in an
array of chars (or simply a string) and not in an array of integers. So when i want a string to hold 20 characters i need to declare char string[21];. When i want to declare an array of integers holding 5 digits then int digits[5]; is enough. What is the reason for this?
You don't have to terminate a char array with NULL if you don't want to, but when using them to represent a string, then you need to do it because C uses null-terminated strings to represent its strings. When you use functions that operate on strings (like strlen for string-length or using printf to output a string), then those functions will read through the data until a NULL is encountered. If one isn't present, then you would likely run into buffer overflow or similar access violation/segmentation fault problems.
In short: that's how C represents string data.
Null terminators are required at the end of strings (or character arrays) because:
Most standard library string functions expect the null character to be there. It's put there in lieu of passing an explicit string length (though some functions require that instead.)
By design, the NUL character (ASCII 0x00) is used to designate the end of strings. Hence why it's also used as an EOF character when reading from ASCII files or streams.
Technically, if you're doing your own string manipulation with your own coded functions, you don't need a null terminator; you just need to keep track of how long the string is. But, if you use just about anything standardized, it will expect it.
It is only by convention that C strings end in the ascii nul character. (That's actually something different than NULL.)
If you like, you can begin your strings with a nul byte, or randomly include nul bytes in the middle of strings. You will then need your own library.
So the answer is: all arrays must allocate space for all of their elements. Your "20 character string" is simply a 21-character string, including the nul byte.
The reason is it was a design choice of the original implementors. A null terminated string gives you a way to pass an array into a function and not pass the size. With an integer array you must always pass the size. Ints convention of the language nothing more you could rewrite every string function in c with out using a null terminator but you would allways have to keep track of your array size.
The purpose of null termination in strings is so that the parser knows when to stop iterating through the array of characters.
So, when you use printf with the %s format character, it's essentially doing this:
int i = 0;
while(input[i] != '\0') {
output(input[i]);
i++;
}
This concept is commonly known as a sentinel.
It's not about declaring an array that's one-bigger, it's really about how we choose to define strings in C.
C strings by convention are considered to be a series of characters terminated by a final NUL character, as you know. This is baked into the language in the form of interpreting "string literals", and is adopted by all the standard library functions like strcpy and printf and etc. Everyone agrees that this is how we'll do strings in C, and that character is there to tell those functions where the string stops.
Looking at your question the other way around, the reason you don't do something similar in your arrays of integers is because you have some other way of knowing how long the array is-- either you pass around a length with it, or it has some assumed size. Strings could work this way in C, or have some other structure to them, but they don't -- the guys at Bell Labs decided that "strings" would be a standard array of characters, but would always have the terminating NUL so you'd know where it ended. (This was a good tradeoff at that time.)
It's not absolutely necessary to have the character array be 21 elements. It's only necessary if you follow the (nearly always assumed) convention that the twenty characters be followed by a null terminator. There is usually no such convention for a terminator in integer and other arrays.
Because of the the technical reasons of how C Strings are implemented compared to other conventions
Actually - you don't have to NUL-terminate your strings if you don't want to!
The only problem is you have to re-write all the string libraries because they depend on them. It's just a matter of doing it the way the library expects if you want to use their functionality.
Just like I have to bring home your daughter at midnight if I wish to date her - just an agreement with the library (or in this case, the father).
Just wondering why this is the case. I'm eager to know more about low level languages, and I'm only into the basics of C and this is already confusing me.
Do languages like PHP automatically null terminate strings as they are being interpreted and / or parsed?
From Joel's excellent article on the topic:
Remember the way strings work in C: they consist of a bunch of bytes followed by a null character, which has the value 0. This has two obvious implications:
There is no way to know where the string ends (that is, the string length) without moving through it, looking for the null character at the end.
Your string can't have any zeros in it. So you can't store an arbitrary binary blob like a JPEG picture in a C string.
Why do C strings work this way? It's because the PDP-7 microprocessor, on which UNIX and the C programming language were invented, had an ASCIZ string type. ASCIZ meant "ASCII with a Z (zero) at the end."
Is this the only way to store strings? No, in fact, it's one of the worst ways to store strings. For non-trivial programs, APIs, operating systems, class libraries, you should avoid ASCIZ strings like the plague.
Think about what memory is: a contiguous block of byte-sized units that can be filled with any bit patterns.
2a c6 90 f6
A character is simply one of those bit patterns. Its meaning as a string is determined by how you treat it. If you looked at the same part of memory, but using an integer view (or some other type), you'd get a different value.
If you have a variable which is a pointer to the start of a bunch of characters in memory, you must know when that string ends and the next piece of data (or garbage) begins.
Example
Let's look at this string in memory...
H e l l o , w o r l d ! \0
^
|
+------ Pointer to string
...we can see that the string logically ends after the ! character. If there were no \0 (or any other method to determine its end), how would we know when seeking through memory that we had finished with that string? Other languages carry the string length around with the string type to solve this.
I asked this question when my underlying knowledge of computers was limited, and this is the answer that would have helped many years ago. I hope it helps someone else too. :)
C strings are arrays of chars, and a C array is just a pointer to a memory location, which is the start location of the array. But also the length (or end) of the array must be expressed somehow; in case of strings, a null termination is used. Another alternative would be to somehow carry the length of the string alongside with the memory pointer, or to put the length in the first array location, or whatever. It's just a matter of convention.
Higher level languages like Java or PHP store the size information with the array automatically & transparently, so the user needn't worry about them.
C has no notion of strings by itself. Strings are simply arrays of chars (or wchars for unicode and such).
Due to those facts C has no way to check i.e. the length of the string as there is no "mystring->length", there is no length value set somewhere. The only way to find the end of the string is to iterate over it and check for the \0.
There are string-libraries for C which use structs like
struct string {
int length;
char *data;
};
to remove the need for the \0-termination but this is not standard C.
Languages like C++, PHP, Perl, etc have their own internal string libraries which often have a seperate length field that speeds up some string functions and remove the need for the \0.
Some other languages (like Pascal) use a string type that is called (suprisingly) Pascal String, it stores the length in the first byte of the string which is the reason why those strings are limited to a length of 255 characters.
Because in C strings are just a sequence of characters accessed viua a pointer to the first character.
There is no space in a pointer to store the length so you need some indication of where the end of the string is.
In C it was decided that this would be indicated by a null character.
In pascal, for example, the length of a string is recorded in the byte immediately preceding the pointer, hence why pascal strings have a maximum length of 255 characters.
It is a convention - one could have implemented it with another algorithm (e.g. length at the beginning of the buffer).
In a "low level" language such as assembler, it is easy to test for "NULL" efficiently: that might have ease the decision to go with NULL terminated strings as opposed of keeping track of a length counter.
They need to be null terminated so you know how long they are. And yes, they are simply arrays of char.
Higher level languages like PHP may choose to hide the null termination from you or not use it at all - they may maintain a length, for example. C doesn't do it that way because of the overhead involved. High level languages may also not implement strings as an array of char - they could (and some do) implement them as lists of arrays of char, for example.
In C strings are represented by an array of characters allocated in a contiguous block of memory and thus there must either be an indicator stating the end of the block (ie. the null character), or a way of storing the length (like Pascal strings which are prefixed by a length).
In languages like PHP,Perl,C# etc.. strings may or may not have complex data structures so you cannot assume they have a null character. As a contrived example, you could have a language that represents a string like so:
class string
{
int length;
char[] data;
}
but you only see it as a regular string with no length field, as this can be calculated by the runtime environment of the language and is only used internally by it to allocate and access memory correctly.
They are null-terminated because whole plenty of Standard Library functions expects them to be.