retagged by
1,497 views
0 votes
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?
retagged by

4 Answers

Best answer
0 votes
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 votes
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 votes
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

Related questions

0 votes
0 votes
1 answer
2
1 votes
1 votes
2 answers
4
go_editor asked Mar 26, 2020
1,502 views
After $3$ calls of the $c$ function bug ( ) below, the values of $i$ and $j$ will be :int j = 1; bug () { static int i = 0; int j = 0; i++; j++; return (i); }$i = 0, j = ...