Strings
Strings
String Literals vs Character Arrays
C has three main ways to declare strings.
String literal.
Creates a pointer that points to a string in read-only memory.
Cannot be changed but easy to declare and use.
Character array
Creates a pointer that point to a block of memory on stack frame.
Can be changed but not resized
Dynamically allocated strings
Creates a pointer to a block of memory on the heap.
Can be resized, changed but needs to de-allocated to prevent memory leaks.
Internal representation of strings
The end of strings is specified by a special character ‘\0’
char str[] = “This is a string”; -> “This is a string\0”;
String Literals vs Character Arrays
String features in c
String.h gives a bunch of useful functions for handling strings in c.
Strcpy: makes a copy by value of a string
Strcat: concatenates two string (be careful about memory!).
Strlen: computes the length of a string
Strcmp: compare two strings
Example
Arrays of strings
Char planets[][8] ={“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”, “Neptune”, “Pluto?”};
M E R C U R Y \0
V E N U S \0 \0 \0
E A R T H \0 \0 \0
M A R S \0 \0 \0 \0
J U P I T E R \0
S A T U R N \0 \0
U R A N U S \0 \0
N E P T U N E \0
P L U T O ? \0 \0
Array of string literals
Char *planets[] = {“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”, “Neptune”, “Pluto?”}
/docProps/thumbnail.jpeg