CHARACTER STRINGS
char nameArray[10] = "value";
* compiler counts the number of characters inside the string
* compiler reserves memory for the string but gets one character more than the
string's length
- the extra character is for the null terminator
* compiler copies the entire string from the source code into the reserved memory
and appends an empty character at the end;
- the compiler treats the string as a pointer to the reserved memory
* a string is stored as a sequence of characters followed by the empty character
but behaves as a pointer of type char
#WARNING - THIS IS NOT ALLOWED!
char protagonist[20];
protagonist = "Gandalf";
* this is because the pointer "protagonist" points to only the first element of the
array; the assignment tries to force the compiler to change the meaning of the
pointer which is not allowed!
#PREFERRED SOLUTION
#include <string.h>
char protagonist[20];
strcpy(protagonist, "Gandalf");
DISTINCTION
char protagonist[10] = "Frodo";
* an array of 10 characters will be created;
* the following characters: 'F', 'r', 'o', 'd', 'o' and '\ 0' will be stored in the
variable;
* whenever you use the name protagonist it’ll be interpreted as a pointer to the
first element i.e. the one that contains the letter 'F'.
char *hero = "Dumbledore";
* the compiler reserves the memory of 11 bytes (10 for the hero's name itself + 1 for
an empty char) and fills it with the
characters 'D', 'u', 'm', 'b', 'l', 'e' , 'd', 'o', 'r' , 'e' and '\0';
* the compiler creates a variable named hero of type char *;
* the compiler assigns the pointer to a newly reserved string to the hero variable.
strcpy(hero, "Frodo");
Last updated