Pointers और Memory

Pointers और Addresses

Pointer compatible type के object का address रखता है।

Pointers और Addresses क्या है?

Pointer compatible type के object का address रखता है।

Address store, dereference और original object modify करें।

महत्वपूर्ण बातें

  • Pointer किसी जीवित compatible object को point करे या null हो।
  • हर owned allocation को ठीक एक बार release करें।
  • Ownership और const interfaces स्पष्ट रखें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

int main(void) {
    int score = 70;
    int *score_ptr = &score;
    *score_ptr += 5;
    printf("score=%d same-address=%s\n", score,
           score_ptr == &score ? "yes" : "no");
    return 0;
}
अपेक्षित output
score=75 same-address=yes
C++
कोड चलाएँ →
main.cpp
#include <iostream>

int main() {
    int score = 70;
    int* score_ptr = &score;
    *score_ptr += 5;
    std::cout << "score=" << score << " same-address="
              << std::boolalpha << (score_ptr == &score) << '\n';
}
अपेक्षित output
score=75 same-address=true

C और C++ की तुलना

C raw pointer सीधे उपयोग करता है। C++ non-owning access में इसे रखता है, लेकिन null न चाहिए तो reference बेहतर है।

C

Ownership और cleanup programmer द्वारा लागू conventions हैं।

C++

Containers और RAII ownership को object lifetime से जोड़ते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • Null और allocation failure paths test करें।
  • AddressSanitizer और UndefinedBehaviorSanitizer चलाएँ।
  • हर pointer का ownership लिखें।