Created: 2023-01-10 15:23
Status: #concept
Subject: Programming
Tags: C C Array C String
String Literal
AKA: String Constant, Constant String
A C Array of Characters enclosed in double quotation marks ""
.
// a single string literal
puts("When you come to a fork in the road, take it.");
// adjacent string literals are concatenated into a single literal
puts("I am string one" " I am string two\n"
"I am string three");
- In C, every C String ends with a Null Terminator character
\0
which denotes the end of the string so that functions may properly read strings. - We can print string literals using the
printf
function from the<stdio.h>
Library. - They are Nonoverlapping Objects that are allocated when the program is run.
- We reference that read-only memory to access the string literals preprocessed by the Compiler.
Escape Sequences
When using a combination of a backslash character
\
and another specific character, you can "escape" into different characters not usually accessible with the keyboard.
- an exception of this is the
%%
character which prints a%
.
Escape sequence | Character represented |
---|---|
\a |
Alert (bell, alarm) |
\b |
Backspace |
\f |
Form feed (new page) |
\n |
New line (Enter key) |
\r |
Carriage return |
\t |
Horizontal tab |
\v |
Vertical tab |
\' |
Single quotation mark |
\" |
Double quotation mark |
\? |
Question mark |
\\ |
Backslash |
\0 |
Null Terminator |
Operations with String Literals
char *str;
str = "abc"; // pointer address points to the first element of {'a','b','c','\0'}
char ch;
ch = "abc"[1]; // sets ch to 'b'
Common Pitfalls
We cannot edit the individual characters of a String Literal, we have to use a String Variable instead.
char *literal = "I cannot change my letters, only the string I'm pointing to."
char variable[MAX_LEN+1] = "I can index & change my own letters."
What is the difference between
"a"
and 'a'
? How are Strings treated as in C? How are they internally represented as? How many Bytes do they take up?
-
They are treated as const character Arrays with type
char *
. -
When a C compiler encounters a string literal of length
n
, it sets asiden+1
bytes of memory for the string literal. -
This area of memory will contain the characters in the string, +1 extra character — the Null Terminator
\0
- (value of 0 in ASCII while the character '0' is 48)
What operations or Functions can we perform on String Literals?
- Since String Literals are
const char
Arrays, we can use them wherever C allows achar *
Pointer.
int printf(char *format, arg1, arg2, ...);
int scanf(const char *format, ...);
- We can set
char *
Pointers point to String Literals.
char *p;
p = "abc"; // pointer address points to the first element of {'a','b','c','\0'}
- We can also subscript them using
[]
, similar to C Arrays.
char ch;
ch = "abc"[1]; // sets ch to 'b'
References
- C Programming, A Modern Approach, 2nd Edition, Chapter 2.2