Pointers और Memory

Multidimensional Arrays

Built-in 2D array दोनों भाषाओं में row-wise contiguous होता है।

Multidimensional Arrays क्या है?

Built-in 2D array दोनों भाषाओं में row-wise contiguous होता है।

Row-major matrix traverse कर row totals निकालें।

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

  • 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 matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int row = 0; row < 2; ++row) {
        int total = 0;
        for (int column = 0; column < 3; ++column) total += matrix[row][column];
        printf("row %d=%d\n", row, total);
    }
    return 0;
}
अपेक्षित output
row 0=6
row 1=15
C++
कोड चलाएँ →
main.cpp
#include <array>
#include <iostream>

int main() {
    std::array<std::array<int, 3>, 2> matrix{{{{1, 2, 3}}, {{4, 5, 6}}}};
    for (std::size_t row = 0; row < matrix.size(); ++row) {
        int total = 0;
        for (int value : matrix[row]) total += value;
        std::cout << "row " << row << '=' << total << '\n';
    }
}
अपेक्षित output
row 0=6
row 1=15

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

C function को पहली छोड़कर dimensions जाननी होती हैं; std::array dimensions type में रखता और at देता है।

C

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

C++

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

अभ्यास

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

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