C Programming - Strings - Discussion

Discussion Forum : Strings - Find Output of Program (Q.No. 20)
20.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    char str[] = "India\0BIX\0";
    printf("%d\n", sizeof(str));
    return 0;
}
10
6
5
11
Answer: Option
Explanation:

The following examples may help you understand this problem:

1. sizeof("") returns 1 (1*).

2. sizeof("India") returns 6 (5 + 1*).

3. sizeof("BIX") returns 4 (3 + 1*).

4. sizeof("India\0BIX") returns 10 (5 + 1 + 3 + 1*).
    Here '\0' is considered as 1 char by sizeof() function.

5. sizeof("India\0BIX\0") returns 11 (5 + 1 + 3 + 1 + 1*).
    Here '\0' is considered as 1 char by sizeof() function.

Discussion:
12 comments Page 1 of 2.

Keerthi said:   7 years ago
I am not understanding this, please can you explain me in detail?

Usha.R.T said:   7 years ago
If that is the case for sizeoff(), then how it will detect the end of the string?

And why did it not considered last \0 character in a string?

If it considers \0 character as an end of string then it would be same with the one appeared after India.

Prathap v r said:   9 years ago
If that is the case for sizeoff(), then how it will detect the end of the string?

Anusha said:   1 decade ago
Here what is 1*?

Pragya said:   1 decade ago
In sizeof() function string is not considered to be terminated by the character "\0", whereas in strlen() a string is terminated by "\0", hence the return values differ.

Gurchet said:   1 decade ago
There is difference between strlen() and sizeof():

int main()
{
char str[] = "India\0BIX\0";
printf("%d\n", sizeof(str));


char str2[] = "India\0\BIX\0";
printf("%d\n", strlen(str2));


return 0;
}

Veronica said:   1 decade ago
Why are we considering the whole string instead of India only?

Ankit said:   1 decade ago
Now it is bothering me. Previously you said that only "India" will be inside str. And its true, I just printed str directly in %s mode and also by single character. It only contains India.

But then how sizeof returns 11, why it is considering BIX and all those character. ?

Sima said:   1 decade ago
Ya I agree with suhail \0 indicates end of array

Suhail said:   1 decade ago
While reading \0, then it may think as end of file and stops na?


Post your comments here:

Your comments will be displayed after verification.