edited by
1,124 views
2 votes
2 votes
#include<stdio.h>
struct game{
    int level;
    int score;
    struct player{
        char *name;
    } g2;
} g1;

int main(){
    printf("%d %d %s",g1.level,g1.score,g1.g2.name);
}


 

What will output when you compile and run the above code?

(a) Garbage_value garbage_value garbage_value

(b) 0 0 (null)

(c) Run time error

(d) Compiler error

can anyone tell me whats th answer??

and shoul'nt it give the error for g1.g2.name because name is a charcter pointer we are trying to access it before giving it some memory or initializing it with a value..??(as before accessing pointers,you should initialize them as far as i know,otherwise we get an error)

edited by

1 Answer

Best answer
4 votes
4 votes

Any global/static variable in C is initialized to 0. So, output will be

0 0

For the final one, we are giving name the value 0 and printing it as string. So, this is like printing th string from address 0, which should cause undefined behaviour - can even crash and give segmentation fault.


If we move the structure definition to be inside main as shown below, then the first 2 values are garbage and 3rd one might cause access to invalid memory location depending on the garbage value pointed to by name.

    #include<stdio.h>
    int main(){
        struct game{
        int level;
        int score;
        struct player{
            char *name;
        } g2;
    } g1;
        printf("%d %d %s",g1.level,g1.score,g1.g2.name);
    }
edited by

Related questions

2 votes
2 votes
3 answers
1
Shivani gaikawad asked May 3, 2018
641 views
what will be output printed?
0 votes
0 votes
1 answer
2
ranarajesh495 asked Oct 9, 2018
595 views
If we are taking character as input then how we can check the character against a a range of numbers. Please explain
4 votes
4 votes
1 answer
3
3 votes
3 votes
0 answers
4
nishitshah asked Jan 26, 2018
651 views
Answer given is option C. How ?I gather that the character pointer will point to the first byte of the integer whose value is 255.But after that what should be the soluti...