What is the output of this C code?#include <stdio.h> struct student { char *name; }; struct student s; struct student fun(void) { s.name = "newton"; printf("%s\n", s.name); s.name = "alan"; return s; } void main() { struct student m = fun(); printf("%s\n", m.name); m.name = "turing"; printf("%s\n", s.name);
Question
What is the output of this C code?#include <stdio.h> struct student { char *name; }; struct student s; struct student fun(void) { s.name = "newton"; printf("%s\n", s.name); s.name = "alan"; return s; } void main() { struct student m = fun(); printf("%s\n", m.name); m.name = "turing"; printf("%s\n", s.name);
Solution
The output of the C code will be:
newton alan alan
Here's the step by step explanation:
-
The function
fun()is called in themain()function. -
Inside
fun(), thenamefield of the globalstruct student sis first set to "newton", and then it is printed, so "newton" is the first line of output. -
Then, the
namefield ofsis set to "alan", andsis returned fromfun(). -
The returned
structis assigned tomin themain()function. At this point, bothsandmhave theirnamefield set to "alan". -
The
namefield ofmis printed, so "alan" is the second line of output. -
Then, the
namefield ofmis set to "turing", but this does not affects. -
Finally, the
namefield ofsis printed, so "alan" is the third line of output.
Similar Questions
What is the output of the C Program?
What is the output for the following code?
What will be the output of the following C code?#include <stdio.h>int main() { int i; for (i = 0; i < 5; i++); printf("%d\n", i); return 0;}
What would be the output of the following program? #include <stdio.h> int main( ) { int j=1; while (j <= 255) { printf ( "%c %d\n ", j, j ); j++; } return 0; }
What is the output of this C code?#include <stdio.h>int main(){int a = 2;x = x << 1;printf("%d\n", a);}41Depends on the compilerDepends on the endianness of the machine
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.