Click here to Skip to main content
15,891,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Here, I tried to read the string literal using scanf() function. When I tried to print the string literal using printf() function , I am getting the output as (null). Why is that so?
why I am not getting the string literal which I have read as output?

What I have tried:

#include<stdio.h>
int main()
{
char *c;
scanf("%s",c);
printf("%s",c);
return 0;
}
Posted
Updated 24-Apr-21 19:11pm

1 solution

You need to go back a few steps and re-read your notes on pointers and memory:
C++
char* c;
Creates a pointer to a character called c, but doesn't give it a value.
C++
scanf("%s",c);
Tries to read a string into the memory that c points to.

But since you haven't pointed c at anything, your app fails.

Think of it like this: you stop and ask a stranger for directions. He stands there unmoving and tells you to go "That way, then take the first junction on that side, then the second of this side, then go in that direction for about two miles and take another turning".
Unless he indicates left, right, north, south and so on, his directions are no use to you because his pointers are all missing. If he points "left, then right, then right, north, left" while he says it the directions mean something - but empty pointers are of no use to anyone!

Create an area of memory (either by creating an array of characters, or by using malloc) and assign c to the start of it. Then your code will start to work!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900