[Solved] Unexpected output of printf for a string in C


None of those two cases are right.

Case 1 only worked because you got lucky, probably by giving a short string as input. Try something like "bfjabfabjkbfjkasjkvasjkvjksbkjafbskjbfakbsjfbjasbfjasbfkjabsjfkbaksbfjasbfkja" and you’ll suffer a seg fault, most likely.

You should have a block of memory associated with str, either on the stack by declaring an array for it or on the heap malloc‘ing memory for it.

And you shouldn’t use the & operator.

So it would go like this:

#include <stdio.h>
int main()
{
    char str[50];   // 50 is arbitrary
    scanf("%s",str);
    printf("%s",str);
    return 0;
}

or like this:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char* str = malloc(50);   // 50 is arbitrary
    scanf("%s",str);
    printf("%s",str);
    free(str);
    return 0;
}

4

solved Unexpected output of printf for a string in C