C Strings
- Strings aren’t actually strings in C, they’re pointers (of
char
type)
String variables
String initializers
- But these 2 are subtly different.
- (Immutable) The first one is a pointer to a string literal (i.e a pointer to the first char in a string)
- (Mutable) The second one is different, it’s a mutable copy of the string that we can change at will:
String length
When you’re making a new language, you have basically two options for storing a string in memory:
-
- Store the bytes of the string along with a number indicating the length of the string.
-
- Store the bytes of the string, and mark the end of the string with a special byte called the terminator.
If you want strings longer than 255 characters, option 1 requires at least two bytes to store the length. Whereas option 2 only requires one byte to terminate the string. So a bit of savings there, so C took approach #2.
In C, a “string” is defined by 2 basics characteristics:
- A pointer to the first character in the string
- A Zero-valued byte ( or
NUL
character) somewhere in memory after that pointer that indicates the end of the string
- Getting string length:
- Behind the scene, the
strlen()
basically looks like this:
String copy
- Use
strcpy
- Use
memcpy