-3

Instead of pointer char *s if I use array char s[100] (in line 4) the code gets executed. Why is that?

#include<stdio.h>
int main(){
    int l=0;
    char *s;
    printf("enter string : \n");
    fgets(s,100,stdin);
    puts(s);
    while(s[l]!='\0'){
        l++;
    }
    printf("length : %d",l-1);
    return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Rejeo
  • 1

1 Answers1

2

Because you haven't allocated any memory for s, nor even initialized it to a known value.

That means fgets() is scribbling onto some random address, and your program crashes.

With a local char s[100]; you allocate 100 bytes on the stack, and the value of s is a pointer to the zeroth byte of that allocation.

AKX
  • 152,115
  • 15
  • 115
  • 172