อาร์เรย์ เป็นโครงสร้างข้อมูลเชิงเส้นที่เก็บองค์ประกอบประเภทข้อมูลเดียวกัน ในการเข้าถึงองค์ประกอบข้อมูลเดียวของอาร์เรย์ มีวิธีมาตรฐานที่ใช้กันทั่วไป
ไวยากรณ์
array_name[index];
ตัวอย่าง
#include <iostream>
using namespace std;
int main( ){
int arr[2] = {32,65};
printf("First Element = %d\n",arr[0]);
printf("Second Element = %d\n",arr[1]);
return 0;
} ผลลัพธ์
First Element = 32 Second Element = 65
ขณะนี้ มีอีกวิธีหนึ่งที่สามารถให้ผลลัพธ์เดียวกันกับข้างต้นได้
ไวยากรณ์
index[array_name];
ตัวอย่าง
#include <iostream>
using namespace std;
int main( ){
int arr[2] = {32,65};
printf("First Element = %d\n",0[arr]);
printf("Second Element = %d\n",1[arr]);
return 0;
} ผลลัพธ์
First Element = 32 Second Element = 65
ลองพิจารณาทั้งสองกรณี -
arr[0] จะเป็นตัวชี้ *(arr + 0) ที่ชี้ไปที่ค่า
0[arr] จะเป็น *(0 + arr) ตัวชี้ที่ชี้เหมือนกับตัวก่อนหน้า
ตัวชี้ทั้งสองชี้ไปยังที่อยู่หน่วยความจำเดียวกัน