Array หลายมิติ
Built-in 2D array เก็บต่อเนื่องตามแถวในทั้งสองภาษา
Array หลายมิติ คืออะไร?
Built-in 2D array เก็บต่อเนื่องตามแถวในทั้งสองภาษา
วน matrix แบบ row-major และหาผลรวมแต่ละแถว
ประเด็นสำคัญ
- Pointer ต้องชี้ object ที่ยังมีชีวิตและ type ตรงกันหรือเป็น null
- Allocation ที่เป็นเจ้าของต้องถูก free เพียงครั้งเดียว
- ระบุ ownership และ const ให้ชัดเจน
ตัวอย่างโค้ด C และ 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;
}
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';
}
}
row 0=6
row 1=15
เปรียบเทียบ C และ C++
ฟังก์ชัน C ต้องรู้ dimension ยกเว้นตัวแรก ส่วน std::array เก็บ dimension ใน type และมี at
C
Ownership และ cleanup เป็นกฎที่โปรแกรมเมอร์ต้องดูแล
C++
Container และ RAII ผูก ownership กับ lifetime ของ object
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- ทดสอบ null และ allocation failure
- ใช้ AddressSanitizer และ UndefinedBehaviorSanitizer
- บันทึก ownership ของ pointer ทุกตัว