Pointer Arithmetic
Typed pointer में एक जोड़ने पर एक byte नहीं, पूरा element आगे बढ़ता है।
Pointer Arithmetic क्या है?
Typed pointer में एक जोड़ने पर एक byte नहीं, पूरा element आगे बढ़ता है।
Pointers और iterators से contiguous memory चलें।
महत्वपूर्ण बातें
- Pointer किसी जीवित compatible object को point करे या null हो।
- हर owned allocation को ठीक एक बार release करें।
- Ownership और const interfaces स्पष्ट रखें।
C और C++ code examples
main.c
#include <stdio.h>
int main(void) {
int values[] = {10, 20, 30, 40};
int sum = 0;
for (int *p = values; p < values + 4; ++p) sum += *p;
printf("sum=%d distance=%td\n", sum, (values + 4) - values);
return 0;
}
sum=100 distance=4
C++
main.cpp
#include <iostream>
#include <vector>
int main() {
std::vector values{10, 20, 30, 40};
int sum = 0;
for (auto it = values.begin(); it != values.end(); ++it) sum += *it;
std::cout << "sum=" << sum << " distance="
<< std::distance(values.begin(), values.end()) << '\n';
}
sum=100 distance=4
C और C++ की तुलना
यह समान array में one-past-end तक defined है; C++ iterator यही traversal containers तक बढ़ाता है।
C
Ownership और cleanup programmer द्वारा लागू conventions हैं।
C++
Containers और RAII ownership को object lifetime से जोड़ते हैं।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Null और allocation failure paths test करें।
- AddressSanitizer और UndefinedBehaviorSanitizer चलाएँ।
- हर pointer का ownership लिखें।