614 views
6 6 votes

What is the output of the code given below?

#include<stdio.h>
int main()
{
    char name[] = "satellites";
    int len;
    int size;
    len = strlen(name);
    size = sizeof(name);
    printf("%d", len * size);
    return 0;
}
  1. $100$
     
  2. $110$
     
  3. $40$
     
  4. $44$

 

2 Answers

4 4 votes

Answer: b) 110.
The above char array name can be written as below:
char[] name = {'s','a','t','e','T','l','i','t','e','s', '10' };

strlen gives no of characters in a string without the null in the end $=10$.
sizeof gives the no of characters(no of bytes specifically) in a string including the null at the end $=11$
So $11^ * 10=110$.

• edited by
1 flag:
✌ Edit necessary (Rajkumar Chaudhary)
3 3 votes
Answer is 110

Now notice that here in the char name[] = "satellites"; we didn’t defined the size of string / array of chars, so it automatically added the /0 char
So Strlen gives size 10 (excluding null char)
And sizeof gives size 11 (including null char)

If it would have been char name[10] = "satellites"; then there is no space for null char so the Strlen can result in undefined behavior — it could return a huge value or cause a crash.
Sizeof will simply return the size as 10

If it would have been char name[10] = "satellite"; then there is one space left as we have 9 char only so null char will automatically be added.
Strlen = 9
Sizeof = 10

If it would have been char name[10] = "sat"; then there is one space left as we have 9 char only so null char will automatically be added at 4th position.
Strlen = 3
Sizeof = 10
 
Answer:
Position:
Show:

Related questions

6 6 votes
2 2 answers
587
587 views
GO Classes asked Jun 28, 2025
587 views
What is the output of the following code?#include <stdio.h int main() { int val[] = {5, 10, 15}; int *ptr = val; *ptr++ = 20; printf("%d %d %d\n", val[0], ptr , val ); re...
5 5 votes
4 4 answers
894
894 views
GO Classes asked Jun 28, 2025
894 views
Consider the following recursive C function.unsigned int f(unsigned int n) { if (n < 10) printf("%d",n); else { printf("%d", n%10); f(n/10); printf("%d", n%10); } }What d...
4 4 votes
3 3 answers
553
553 views
GO Classes asked Jun 28, 2025
553 views
What string does the following program print?#include <stdio.h #include <string.h void strFunc2 (char A[], int n) { char t; if (n <= 1) return; t = A[0]; A[0] = A[n-1]; A...
6 6 votes
2 2 answers
775
775 views
GO Classes asked Jun 28, 2025
775 views
Let the function g be defined as follows:int g ( int n ) { if (n < 2) return n; return g(n/2); }What is the value returned by the call $\mathrm{g}(142857)$ ?$0$ $1$ $2$ $...