Character array, terminated by a null character .
Defined a number of ways:
Characters enclosed individually with 'single quotes'
char myArray[8] = { 'D', 'e', 'r', 'r', 'i', 'c', 'k', '' } ;
char myArray[ ] = { 'D', 'e', 'r', 'r', 'i', 'c', 'k', '' } ;
or within "double quotes"
char myArray[8] = "Derrick" ;
char myArray[ ] = "Derrick" ;
#include <stdio.h> int main() { char myArray[8] = "Derrick" ; printf("Array elements:n"); for (int i = 0; i < 8; i++) { printf("%d = %c, n", i, myArray[i] ) ; } return 0; }
Compile & run:
0 = D, 1 = e, 2 = r, 3 = r, 4 = i, 5 = c, 6 = k, 7 = , |
notice that the 8th element contains nothing = the NULL character
#include <stdio.h> int main() { char myArray[8] = "Derrick" ; for (int i = 0; i <8; i++) { printf("%c", myArray[i] ) ; } return 0; }
Compile & run:
Derrick |
Alternatively, the %s string format specifier can be used to print the whole string.
#include <stdio.h> int main() { char myArray[ ] = { 'D', 'e', 'r', 'r', 'i', 'c', 'k', '' } ; printf("The array contains: %s n", myArray ) ; return 0; }
Compile & run:
Derrick |
There are a number of predefined functions made to work with strings, to be accessed here!