In: Computer Science
Select all that applies. There may be more than one correct answers. Which of the following is a correct initialization of a C string?
Group of answer choices
string s[20] = "C++";
string s = "C++";
char s[20];
char* s = "C++";
char s[20] = {'C', '+', '+', '\0'};
char s[20] = "";
char s[20] = "C++";
Given choices are:
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’.To represent a string, a set of characters are enclosed within double quotes (").'C' always treats a string a single data even though it contains whitespaces. A single character is defined using single quote representation. A string is represented using double quote marks.
Since it is an array of characters we cannot initialise it as just string.Hence 1 and 2 is incorrect
The third choice char s[20]; is actually declaration of the string of size 20.The basic syntax is char str_name[size];It doesn't come under initialisation.
Now the fourth choice char*s="C++" is correct as this initializes s to the first character of the readonly string "C++"(Pointer).A string initialized through a character pointer cannot be modified.If we try it produces undefines behavior,which is better to avoid.
The choice 5 is correct.When you initialize a character array by listing all of its characters separately then you must supply the '\0' character .To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word.So char s[20] = {'C', '+', '+', '\0'}; is correct
The 6th choice char s[20] = "";is incorrect as assigning string literals to char array is allowed only during declaration not initialisation.
The last choice char s[20] = "C++"; is correct
as we can we can put the array size inside the []
of
the declaration.
Hnece it is convinced that choices 4,5 and 7 are correct.