1,703 views
6 votes
6 votes

Which one among the following definitions of string str could cause problem when passed as the first argument to printf function?

  1. char str[] = "Hello World";
  2. char str[12] = "Hello World";
  3. char *str = "Hello World";
  4. char str[] = {'H','e','l','l','o',' ','W','o','r','l','d'};

4 Answers

Best answer
16 votes
16 votes

We are asked,

Which one among the following definitions of string str could cause a problem when passed as the first argument to printf function?

Option D. char str[] = {'H','e','l','l','o',' ','W','o','r','l','d'};   // It is just a character array but not string. 

Now if we add a null character '\0' at the end of all characters in the above array then it will be string str= Hello World.

And in the rest options, the compiler can automatically append a null character (\0) to the end of the array and treat the character array as a character string.

selected by
0 votes
0 votes
answer (d) is correct becuse d is a character array not a string but all 3 are string declration
0 votes
0 votes

In C a string is defined as an array of characters termined by the NULL terminator, ie, \0.

In Options A, B and C, the compiler would implicitly add a NULL terminator at the end.

In Option D, we're defining the whole character array ourselves and we didn't add the NULL terminator explicitly, which is required here.

0 votes
0 votes
#include <stdio.h>
int main(){
    char Str1[] = "Hello World";
    char Str2[12] = "Hello World";
    char *Str3 = "Hello World";
    char Str4[] = {'H','e','l','l','o',' ','W','o','r','l','d'};
    printf("%s\n",Str4);
    printf("Sizeof Str1 : %d \t Strlen Str1 : %d\n",sizeof(Str1),strlen(Str1));
    printf("Sizeof Str2 : %d \t Strlen Str2 : %d\n",sizeof(Str2),strlen(Str2));
    printf("Sizeof Str3 : %d \t Strlen Str3 : %d\n",sizeof(Str3),strlen(Str3));
    printf("Sizeof Str4 : %d \t Strlen Str4 : %d\n",sizeof(Str4),strlen(Str4));
}

Output : 

Hello World
Sizeof Str1 : 12 	 Strlen Str1 : 11
Sizeof Str2 : 12 	 Strlen Str2 : 11
Sizeof Str3 : 8 	 Strlen Str3 : 11  
Sizeof Str4 : 11 	 Strlen Str4 : 11  

You will Not get any Error that's correct But, If you see the String4 sizeof(Str4).  i.e 11 which means the compiler is not adding the '\0' in Str4.

Sizeof (Str3) is 8 because its pointer type variable (i.e Sizeof(pointer) = 8 Byte

For all remaining String from Str1, Str2, Str3 the compiler Implicit added the '\0'     

Answer:

Related questions

3 votes
3 votes
2 answers
2
8 votes
8 votes
2 answers
3
1 votes
1 votes
3 answers
4