C Programming - Strings - Discussion

28. 

If the size of pointer is 4 bytes then What will be the output of the program ?

#include<stdio.h>

int main()
{
    char *str[] = {"Frogs", "Do", "Not", "Die", "They", "Croak!"};
    printf("%d, %d", sizeof(str), strlen(str[0]));
    return 0;
}

[A]. 22, 4
[B]. 25, 5
[C]. 24, 5
[D]. 20, 2

Answer: Option C

Explanation:

Step 1: char *str[] = {"Frogs", "Do", "Not", "Die", "They", "Croak!"}; The variable str is declared as an pointer to the array of 6 strings.

Step 2: printf("%d, %d", sizeof(str), strlen(str[0]));

sizeof(str) denotes 6 * 4 bytes = 24 bytes. Hence it prints '24'

strlen(str[0])); becomes strlen(Frogs)). Hence it prints '5';

Hence the output of the program is 24, 5

Hint: If you run the above code in 16 bit platform (Turbo C under DOS) the output will be 12, 5. Because the pointer occupies only 2 bytes. If you run the above code in Linux (32 bit platform), the output will be 24, 5 (because the size of pointer is 4 bytes).


Susanta said: (Aug 21, 2011)  
So what is the declaration of array of pointer?

Ankur Chaurasiya said: (Feb 11, 2015)  
Can you explain it in detail?

Anubhav Singh said: (Jun 20, 2015)  
*str[] is declared as the array of pointer not the pointer to an array.

Then, str points to the base address of the declaration i.e., to the "frogs",

Size of frogs is 6*4 (because the format specifier is of int),

Similarly strlen (str[0]) => strlen ("frogs") which will give 5.

Note that, sizeof counts the '\0' character at the end of string for calculation whereas strlen does not.

Anonymous said: (Oct 26, 2015)  
How come strlen (str[0]) will work? Without using #include<string.h>.

Deepak Chauhan said: (Feb 3, 2016)  
Here pointer array consist of 6 strings and size of pointer is 4 byte in 32 bit system and 8 byte in 64 bit system.

Hence 6 strings* 4 byte each = 24 byte is sizeof str.

While string length of "frogs" is 5 since it consist of 5 character.

Renuvicky said: (Dec 27, 2016)  
Can you explain it in detail?

Amogh Gowda said: (Jul 2, 2017)  
@Anubhav Singh.

You said sizeof will count \0 also then in str there are 6 strings=6*4=24.

And one null character so it should be 24+1=25.

Bunny said: (Jul 2, 2018)  
Previously we counted a null character in "sizeof () " function but in this question we didn't why? Please explain.

Utkarsh said: (Jun 2, 2019)  
@All.

Here is what I found:

Linux GCC on Ubuntu 18.04 gives output:
48 and 5.


Turbo C/C++ 3.2 gives output:
10 and 5.

Which is correct one, Please anyone tell me.

Balaji said: (Aug 4, 2020)  
Initially we know that the size of the operator will give one extra value because

it is a[] = "hello";
sizeof(a) -> 5+1 -> 6;
because it is a single string.
And here it is an array of the pointer so it gives the array size.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.