Introduction
Strings are an essential part of programming and programming language. In C/C++, there are two ways to represent them: string literals and character arrays. In this blog, we will delve deep into the string literals and character arrays in C/C++.
String Literal:
Definition:
A string literal in C/C++ is a sequence of character enclosed in double quotation marks. For example:
// In C
char* strLiteral = "Hello, World!";
// In C++
const char* strLiteral = "Hello, World!";
Here, strLiteral is basically a pointer to the (const) string literal.
Characteristics:
- Read-only Memory: String literals are stored in read-only memory, which means attempting to modify them directly results in undefined behavior (segmentation fault).
- Null-terminated: String literals are null-terminated, meaning they end with a null character (
\0
), marking the end of the string. - In C this works fine, Because in C string literals are arrays of char but in C++ they are constant array of char. Therefore use const keyword before char*.
- No need to declare the size of string beforehand.
Cons:
- We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str.
Example:
const char* greeting = "Hello";
Character Array
Definition:
A character array in C/C++ is a sequence of characters stored in contiguous memory locations. It is declared as an array of characters and can be modified during program execution.
char charArray[] = "Hello, World!";
or
char charArray[size] = "Hello, World!";
Here, greeting
is a character array that can be modified.
Characteristics:
- Mutable: Unlike string literals, character arrays are mutable, allowing you to modify their contents during runtime.
- Size Specification: The size of a character array should be carefully specified to avoid buffer overflows.
Cons:
- This is statically allocated sized array which consumes space in the stack.
- We need to take the large size of array if we want to concatenate or manipulate with other strings since the size of string is fixed.