why printf is not showing string on removing & and not showing address in C?

1972 views c
2

#include<stdio.h>

void main(){

char *r;
printf("Enter the string : ");
scanf("%s",&r); 
printf("\nThe string is : %s",&r);

}

i am using DEV C++ (tdm-gcc 4.9.2 64-bit release) in printf statment & removal will lead to printing of string but it is showing no output which confuses me alot and i read that we can also use scan without & in case of string but it also not working in C

answered question

Oh my... You have read a string into the area of memory on your stack that is meant to hold a pointer. If you remove the & for both scanf and printf calls, it would be nearly correct except you need to actually initialize the pointer by allocating some memory first.

You're not allocating any memory

1 Answer

4

The %s format specifier to scanf expect a pointer to the first element of an array of char. In other words, a char *. You are instead passing a char **. Using the wrong format specifier invokes undefined behavior.

Define r as an array:

char r[100];

Then you can pass r to scanf, which decays into a pointer to the first element:

scanf("%99s", r);

Note also that we specify a maximum length here so that there is no risk of writing past the end of the array if too many characters are entered.

Similarly with printf, you need to call it as follows:

printf("\nThe string is : %s",r);

posted this

Have an answer?

JD

Please login first before posting an answer.