Loading...

String Literal vs Character Array in C/C++

String Literal vs Character Array in C/C++

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:

  1. Read-only Memory: String literals are stored in read-only memory, which means attempting to modify them directly results in undefined behavior (segmentation fault).
  2. Null-terminated: String literals are null-terminated, meaning they end with a null character (\0), marking the end of the string.
  3. 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*.
  4. No need to declare the size of string beforehand.

Cons:

  1. 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:

  1. Mutable: Unlike string literals, character arrays are mutable, allowing you to modify their contents during runtime.
  2. Size Specification: The size of a character array should be carefully specified to avoid buffer overflows.

Cons:

  1. This is statically allocated sized array which consumes space in the stack.
  2. 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.
The Admin

The Admin

And yet you incessantly stand on their slates, when the White Rabbit: it was YOUR table,' said.