2

I would like to know, is that possible to initialize the structure1 by structure2. I am new to the concept of casting too. The output of this code has to be zero. Please guide. Thanks!

#include<stdio.h>

typedef struct student
{
 int roll_id[10];
 int name_id[10];
 int postn;
} student;

typedef struct exams
{
int subject[10];
int area;
}exams;

int main()
{
 exams e= { {0} };
 student *pptr= (student*)&e;
 printf (" %d\n", pptr->name_id[9]);
 return 0;
 }
Swetha.P
  • 81
  • 2
  • 8

2 Answers2

2

Analogy is simple:
You buy an Apple and pretend it is an Orange.
As long as you eat it as something eatable you can eat it, but If you bite in to it expecting to get orange juice you will end up disappointed.

Replace Apple & Orange by your two structures and you by compiler.

Structure is nothing but a block of memory which is usually occupied by different data types.
The compiler implementation may add padding bytes between these types except for the first type in the structure.
Since the first type of your both structures is same(an array of 10 integers). Pretending the structure exam as of other type, student will work but if you try to access any other data type other than the first type it will result in Undefined Behavior.

Undefined Behavior is what you are getting in your code.

Bottom line:
You cannot do this.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

First of all, in your code you are not initializing structure1 by structure2, but merely disguising pointer to structure2 as a pointer to structure1.

exams structure instance apparently (let alone weird alignment settings) takes less memory than student instance. Accessing pptr->name_id[9] can very well result in reading past the area dedicated to e. Now it all depends upon your compiler, your computer and so on.. meaning that it is better avoid delving into such details for one's sake.

The output of this code has to be zero

Perhaps it is if you are reading from unallocated stack area (past e) and in your setup stack is filled with zeroes before handing it over to the running thread.

Please read more in your C book about casting and automatic memories and instances and pointers. There is really so much to tell to right your code. You would be better off asking more specific questions after you've studied on the topic more. Good luck

Roman Saveljev
  • 2,544
  • 1
  • 21
  • 20