Interview Questions

C - Variables Second Round

In the previous chapter, we saw that a character variable can hold 1 byte of value. How do I store a value – say “techdive” in a character variable. It is not possible in a character variable that holds 1 byte of value. Here the value “techdive” seems to hold more than 1 byte of value. What is the solution?

C offers a data type that is an extension of character variable, called as a String/Array of characters. Although there is a small difference between these two, which we will see in later chapters. You can create a string/array of characters by specifying the syntax as char variableName[size of the array].

Let us take an example:

#include <stdio.h>
Void main(void)
{
Char myChar = ‘a’;
Char myString[10] = “techdive”; /* creating an array of characters by specifying the size within square brackets and assigning value stated within double quotes */
/* let us print the value */
Printf (%c\n”, myChar); /* printing the value of character */
Printf (%s\n”, myString);  /* printing the string. Format specifier is %s */
}

The program prints the values the output like this:

a
techdive

You can see the difference between the two variables explicitly. String/Array of characters can be initialized by specifying the value within double quotes. Alternatively that statement can also be written as follows:

Char myString[10] = {‘t’,’e’,’c’,’h’,’d’,’i’,’v’,’e’}; /* although this is not a preferred way of initializing */

If you have noted we specified the size of the variable as 10 instead of 8. If you specify it as 8, you can only assign 8 characters precisely. In such a case it is called as “Array of 8 characters”. However there are 2 more bytes present here. 9th position here includes what is known as “NULL “ denoted as \0 – backward slash zero. That basically tells the compiler to assign only specified characters and to stop looking beyond the specified characters. This is a very important concept in C. If NULL is not specified or if you try to print beyond the specified number of characters, run time error (segmentation violation) could occur. In our program, when we initialized the variable within double quotes, it automatically added NULL at the 9th position.

So key takeaways from this chapter:
1. Array of characters/String can be declared by specifying the size within square brackets.
2. NULL character at the end of array/string is a mandatory and if not handled properly, it will lead to the classic run time error of segmentation violation.
3. The size of the array/string is always +1 of the actual number of characters in the value.
4. Printing of an array can be done using the variable name and format specifier as %s.

Let us C more...