edited by
2,415 views
1 votes
1 votes
main ()
{
    struct xx {
        int x = 3;
        char name[] = "hello";
    };
    struct xx *s;
    printf("%d", s->x);
    printf("%s", s->name);
}

The output is :

  1. 3hello
  2. 104ello
  3. 104hello
  4. Compiler error
edited by

1 Answer

Best answer
4 votes
4 votes

C is a very simple language and it is easy to understand everything about it - at least the most common part. Unfortunately this does not happen in Engineering colleges in India and I also have experienced it. In IISc., making a C compiler is just a subject assignment - because it is only that much. 

To answer the above question only 2 things are needed and both everyone knows. 

What does 

struct xx *s;

This creates a pointer s, which can point to an object of type struct s.

printf("%d", s->x);

What does "->" operator does? s->x is nothing but (*s).x.
*s goes to the memory address contained in s (not the address of s), and takes the value from there (amount of data taken is based on the type of s).

So, now I guess answer should be clear here. Yes, the given code is doing invalid memory access and hence should give runtime error. 

But, the given code has another major error, which is that it is initializing structure member variables inside structure definition. This is not allowed in C and will cause compile error. 

selected by

Related questions

0 votes
0 votes
1 answer
2
Desert_Warrior asked Jun 4, 2016
616 views
0 votes
0 votes
1 answer
3
Desert_Warrior asked Jun 2, 2016
704 views
void main() { int i=100,j=10,k; int *p=&j; k=i/(*p); printf("%d",k); }OPTIONS : [ a] 0 [b] 10 [c] 100 [d] None of the above
0 votes
0 votes
1 answer
4
Desert_Warrior asked Jun 2, 2016
375 views