• retagged by
2,140 views
0 0 votes
For the following program:

#include<stdio.h>
char *getString()
{
char *str = "GfG";
return str;
 }
int main()
{getString();
printf("%s", str); // Gives error, but printf("%s", getString()); works perfect.
return 0;
}

My doubt is that if we're able to return str as it is present in the shared segment of the memory and it's activation record does not get destroyed, wh can't we print the value using str? Why does the program give error saying that str is undeclared?

4 Answers

Best answer
0 0 votes
For any variable in C we have a scope beyond which we should not use it. "str" is written inside getString function and so main has no idea of it. If you make another global char pointer and assign it the value of str, you can use it inside main.
• selected by
0 0 votes
Since 'str' is local variable to getString method,so it cannot be access by main method.
If you do like this
#include<stdio.h>
char *str;
char *getString()
{
 str = "GfG";
return str;
 }
int main()
{getString();
printf("%s", str);
return 0;
}
Output:Success    time: 0 memory: 10320 signal:0
GfG

Since 'str'  is global variable it can be access from anywhere
0 0 votes
because printf is a function, when you call getstring inside it, the returned result gets replaced in printf and prints it

but  when you call getstring() and dont assign anything to which the result can be stored then how will printf print it

incase you provided str=getstring();

now the reurned value gets stored, if you dont give anything where will it store the value and so it remaiins undeclared to main when printed
Position:
Show:

Related questions

1 1 vote
0 0 answers
425
425 views
deependu asked Apr 23, 2023
425 views
I have seen alot of people saying that we can make an Integer string in C language.But according to me we can only make a character string in C language.here is the code:...
0 0 votes
1 answers 1 answer
1.2k
1.2k views
Bongbirdie asked May 2, 2017
1,245 views
I am trying to implement strcpy manually but am getting error. What is the error? Please help! #include<stdio.h char* cpy(char *a,char *b) { char *arr; arr=&a; ...
7 7 votes
3 3 answers
281
281 views
GO Classes asked Jun 9
281 views
What is the output of the following code?#include <stdio.h int main() { register int x = 10; int *p = &x; printf("%d", *p); return 0; }$\texttt{10}$ $\texttt{0}$ Garbage ...
9 9 votes
2 2 answers
254
254 views
GO Classes asked Jun 9
254 views
What can be said about the output of the following code?#include <stdio.h int main() { auto int x; printf("%d", x); return 0; }Output is always $\texttt{0}$ Output is alw...