AnyCompiler

Structs aur Pointers

Jab aap ke paas ek struct ka pointer hai — jo malloc allocate karne par return karta hai — to aap dot operator directly istemal nahi kar sakte, kyunke p.x ke liye p ko ek asli struct hona chahiye, uska pointer nahi. -> operator ek step mein dereference karke field access karne ka shorthand hai: p->x ka matlab hai (*p).x.

#include <stdio.h>
#include <stdlib.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point *p = malloc(sizeof(struct Point));
    p->x = 3;
    p->y = 4;
    printf("%d %d\n", p->x, p->y);
    free(p);
    return 0;
}
Output
3 4

Real compiler error kaisa dikhta hai

Struct pointer par . istemal karna -> ki jagah ek waqai common C mistake hai, aur compiler use foran pakar leta hai. Ye waqai wahi hai jo gcc report karta hai — ek real run se capture kiya gaya, plausible dikhne ke liye likha nahi gaya:

#include <stdio.h>
#include <stdlib.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point *p = malloc(sizeof(struct Point));
    p.x = 3;
    printf("%d\n", p.x);
    free(p);
    return 0;
}
Output
main.c: In function ‘main’:
main.c:11:6: error: ‘p’ is a pointer; did you mean to use ‘->’?
   11 |     p.x = 3;
      |      ^
      |      ->
main.c:12:21: error: ‘p’ is a pointer; did you mean to use ‘->’?
   12 |     printf("%d\n", p.x);
      |                     ^
      |                     ->

GCC ka diagnostic yahan unusually helpful hai — ye exact fix naam leta hai. Is course ka har compiler error itna forgiving nahi hoga.

Aage: function pointers — ek function ko khud ek variable mein store karna, aur use indirectly call karna.

Practice exercise

Struct Point define karein jiske fields x aur y hon. malloc se ek Point banayein, -> ke through pointer se x ko 3 aur y ko 4 set karein, dono print karein, phir use free karein.