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 2 of 2.

Sundar said:   1 decade ago
Is it possible for the sizeof operator to ever return 0 (zero) in C or C++? If it is possible, is it correct from a standards point of view?

The sizeof() function never returns 0 in C and in C++. Every time you see sizeof evaluating to 0 it is a bug/glitch/extension of a specific compiler that has nothing to do with the language.

Abhishek said:   1 decade ago
How the empty string i.e sizeof("") returns 1?


Post your comments here:

Your comments will be displayed after verification.