A4 - strings
char name[] = "string";
-
here, an array of characters is generated to represent a string
-
each character is stored serially as its ASCII value, terminated by a
nullcharacter -
in the above declaration, an array of length 7 is created
-
special characters are represented using escape sequences
| escape sequence | meaning |
|---|---|
\n |
new line |
\t |
horizontal tab |
\' |
single quote |
\" |
double quote |
\x43 |
ASCII hex (for 'C') |
\0 |
null |
\\ |
backslash |
char name[40]; /* an array that can contain 39 characters */
scanf("%39s", name); /* note that there is no '&' */
printf("hello, %s!\n", name);
-
the name of an array is the address of its first element, so it shouldn't be passed as a reference
-
string operations are contained in a special library,
<string.h>
#include <string.,h>
char dest[100];
strcpy(dest, source); /* dest = source */
strcat(dest, source); /* dest + source */
/* safer string functions that explicity state the maximum size*/
strcpy_s(dest, sizeof(dest), source); /* dest = source */
strcat_s(dest, sizeof(dest), source); /* dest + source */
puts(dest); /* prints out the string with a new line */
char msg[40];
strcat_s(msg, sizeof(msg), "'"hello")
int size = sizeof(msg) /* 40 */
int length = strlen(msg) /* 6 */
strcmp(password, "password" /* comparison: 0 if equal */