Medium ●●

🧱 Structs, Unions & Undefined Behaviour

Why it matters: Layout and sizeof questions test your model of memory; the undefined-behaviour checklist lets you answer "what will this program print?" correctly when the answer is "anything".

Subtopics

Each subtopic has its own page: idea, why, how, example, play, check. Mark each one understood when it clicks. 0 of 4 done.

Formulas

Struct size
sum of members + padding, rounded up to a multiple of the largest member alignment
Offset of a member
round the running offset up to the member's alignment
Union size
size of the largest member (rounded up to the largest alignment)
p->x
(*p).x
Array of structs
element i is at base + i · sizeof(struct)

What GATE asks from this

Question types seen repeatedly in past papers. More stars means more frequent.

★★★
Offset of a struct field (addressing mode)
Add up the sizes of the earlier members to get the displacement.
★★★
Output through a char* cast of a struct pointer
Treat the struct as consecutive bytes; (char*)q + 1 is the second char member.
★★★
Which statements about undefined behaviour are true?
Check each statement against the undefined-behaviour list.

Ratings are approximate, based on recurring patterns in past GATE CSE papers.

Previous year questions

2 real questions from the official GATE CSE papers (2017 to 2018), newest first, each with the official answer key and a worked solution. Questions are the property of the GATE organising institutes; this copy is for your personal study.

2 questions · 0 correct of 0 attempted · marks 0 / 2

Year:
GATE 2018 · Q2MCQ1 mark
Consider the following C program.
#include<stdio.h>
struct Ournode{
  char x,y,z;
};

int main(){
  struct Ournode p = {'1', '0', 'a'+2};
  struct Ournode *q = &p;
  printf ("%c, %c", *((char*)q+1), *((char*)q+2));
  return 0;
}
The output of this program is:
GATE 2017 Set 1 · Q11MCQ1 mark
Consider the C struct defined below:
struct data {
  int marks [100];
  char grade;
  int cnumber;
};
struct data student;
The base address of student is available in register R1. The field student.grade can be accessed efficiently using

Common traps

sizeof(struct) is often larger than the sum of its members.
A union stores one value at a time.
Reading a different union member than the one last written is not portable.
An uninitialised local is garbage, not 0.