Home | API | MFC | C++ | C | Previous | Next

Programming With C

Characters and Strings

C uses the char type to store characters and letters. The char type is considered an integer type. Each char integer value is mapped with a corresponding character using a numerical code. The most common numerical code is ASCII.

Declare a char

In order to declare a variable with character type, use the char keyword followed by the variable name -

char ch;

Initialise a char

A char character variable can be initialised with a character literal or an integer type. A character literal contains one character that is surrounded by a single quotation (‘’).

The following example declares a char variable character and initialises it with a character literal char

ch='a';

Because the type is the integer type, you can initialise or assign a char variable using an integer. -

char ch=65;

Single quotes vs double quotes

In C single quotes identify a single character while double quotes create a string literal. 'a' is a single character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array). 

String literals are constants that represent a sequence of characters which, taken together, form a null-terminated string. All C compilers create a read-only string table which is used to store these string literals used by the program. 

Print characters in C

To print characters in C, use the printf () function with %c as a placeholder. Using %d will output an integer instead of a character.

The following code example demonstrates how to print characters in C using both integers and char literals

/* Declare and initialise two char variables */
char c1 = 'A';
char c2 = 90;
int main( void ) { /* Print variable c1 as a character, then as a number */
printf("\nvariable c1 As a character, is %c", c1);
printf("\nvariable c1 As a number, is %d", c1); /* Do the same for variable c2 */
printf("\nvariable c2 As a character, is %c", c2);
printf("\nvariable c2 As a number, is %d\n", c2);
return 0;
}

Char Arrays

C-strings are arrays of type char terminated with a null character or \0.

To declare and initialise a character string 

Character arrays can be declared and initialised on a character-by-character basis using an array-style initialiser however it's much easier to initialise a character array with a string literal -

char greeting[6] = {'h','e','l','l','o','\0'} (array style initialiser with each array address being initialised individually. NULL character added manually.)
char greeting[] = "hello";(initialisation with a string literal with the compiler calculating the size of the array. The null character is added automatically.)

Initialising a char array with the value '\0' creates a NULL or empty string - 

char greeting[0] = {'\0'};

Inserting '\0' anywhere in the middle of the array would not change the size of the array but it would mean that string processing would stop at that point. Sending the following to the char array to screen would only produce the characters 'hel'

char greeting[] = "hel\0lo" 

Assign new values to a char array

in order to change the contents of the string after the initial assignment, it is necessary to change the contents of the array individually. Assigning the new value to the existing char array ie greetings[]="HELLO" won't work because the = operator isn't defined to copy the contents of a string literal to an array.

greetings[0] = 'H';
greetings[1] = 'E';
greetings[2] = 'L';
greetings[3] = 'L';
greetings[4] = 'O';
greetings[5] = '\0';

Since assigning new array string values individually is not very practical, c uses strcpy/strncpy (found in the string.h header) to assign the contents of an array outside of a declaration. The syntax for strcpy is-

strcpy(greetings,"hello");

Pointers and Arrays

Arrays elements can also be accessed by the use of pointers. The pointer is declared and assigned to the first element of the array. After assigning the array pointer, the individual elements can be accessed by increasing or decreasing the pointer value.

The code sample below outputs the same letters of an array string by using pointers and array indexing

int main()
{
char str[31]="this is a string to array test"; //declares char array
char *pChar='\0';; //declares char pointer and sets to null
pChar=str; //Sets pointer to start of array
int i;
for(i=0; i<=31; i++) {
printf("%c", *(pChar+i));//prints value of char array
}
return 0;
}

Pointers and String Literals

A string literal in c is a sequence of characters enclosed in double quotation marks. Programmers can allocate their own pointers to store and access characters held in string tables. The code sample below creates and prints a string literal -

int main()
{
const char *ptrsl= "this is a string literal.\n"; //creates pointer ptrsl to to start of string array
printf (ptrsl);
return 0;
}


Attempting to modify a string literal using a pointer can result in undefined behaviour so any pointer to a string literal should be declared as a const.

Array of Pointers

An array of pointers to strings is an array of character pointers where each pointer points to the first character of the string or the base address of the string. To declare and initialise an array of pointers to strings.

char *day[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};

Since initialisation of the array is done at the time of declaration then we can omit the size of an array.

Each element of the sports array is a string literal and since a string literal points to the base address of the first character, the base type of each element of the sports array is a pointer to char or (char*).

To access the values pointed to by an array of pointers if is necessary to iterate and dereference each pointer individually.

const int MAX = 7;
int main () {
char *day[] = {"Sunday","Monday","Tuesday", "Wednesday", "Thursday","Friday","Saturday"};
int i = 0; for ( i = 0; i < MAX; i++) { printf("day[%d] = %s\n", i, day[i] );
}
return 0;
}

Home | API | MFC | C++ | C | Previous | Next
The Basics | Variables | Constants | Expressions and Operators | Controlling Program Flow | Input & Output | C++ Functions | Arrays | Characters and Strings | String Manipulation | Pointers | Structures | Unions | File Input and Output | Advanced Pointers | Type Conversion | Dynamic Memory Allocation

Last Updates:25 October 2022