0

So i have 3 codes here,

  1. in first one i haven't initialized the string ! and strlen shows "3" in ans

  2. in 2nd one i initialized it with 3 char and still the same ans "3"

  3. in 3rd i initialized it with 4 char and output is "4"

Sorry guys, if it was too obvious but i am new and so confused why it shows "3" in output in first code.

//1st
#include<stdio.h>
#include<string.h>
int main()
{
    char y[20];
    printf("%d",strlen(y));
    return 0;
}

//2nd
#include<stdio.h>
#include<string.h>
int main()
{
    char y[20]="yas";
    printf("%d",strlen(y));
    return 0;
}
//3rd
#include<stdio.h>
#include<string.h>
int main()
{
    char y[20]="asds";
    printf("%d",strlen(y));
    return 0;
}
YashRM
  • 1
  • 4

2 Answers2

1

What you are seeing in 1) case is undefined behavior. Because the y is uninitialized.

Also strlen returns size_t , the correct format to print its return value is :

printf("strlen(y) = (%zu)\n",strlen(y));

IrAM
  • 1,720
  • 5
  • 18
  • thanks that helps so does `sizeof()` function also returns `size_t` ? – YashRM Jan 29 '21 at 04:19
  • 1
    `sizeof` is **not** a function, it is an operator. You see a lot of `sizeof (type)` when `type` is just a data type, and this is the required form. If you want the size of an object, you simply use `sizeof object`. Anyway, the result is of type `size_t`, right. (It helps if you read the standard.) – the busybee Jan 29 '21 at 07:25
0

the function of strlen will stop when meet '\0'.

in your first code , char y[20] was not initialized. the values in the array could be anything left in the stack. it happened to be that y[3]=='\0'.

so the strlen(y) could be any value in other environment

Paul Yang
  • 346
  • 2
  • 9
  • maybe you are right but i tried it on online compilers and they all gives the same ans but when i change "20" to "100" it gave "4" as output and when i changed it to "10" answer was "0" is this pattern? i am new so sorry if i am giving you hard time with silly questions ! – YashRM Jan 29 '21 at 04:17