ความหมาย
One-dimensional array (1D array) คือกลุ่มข้อมูลชนิดเดียวกัน จัดเก็บในหน่วยความจำต่อเนื่อง ใช้ชื่อเดียว แยกด้วย index
Syntax
datatype array_name[size];
ตัวอย่าง: int a[5]; // 5 integers
Initialization
Compile-time
int a[5] = {10, 20, 30, 40, 50};Runtime
int a[5], i;
for (i = 0; i < 5; i++)
scanf("%d", &a[i]);ตัวอย่างโปรแกรมที่ 1: Compile-time Init
#include <stdio.h>
int main() {
int a[5] = {10, 20, 30, 40, 50};
int i;
printf("Elements: ");
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
return 0;
}ผลลัพธ์
Elements: 10 20 30 40 50
ตัวอย่างโปรแกรมที่ 2: Runtime Init
#include <stdio.h>
int main() {
int a[5], i;
printf("ป้อน 5 ตัวเลข: ");
for (i = 0; i < 5; i++)
scanf("%d", &a[i]);
printf("Elements: ");
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
return 0;
}ผลลัพธ์
ป้อน 5 ตัวเลข: 10 20 30 40 50 Elements: 10 20 30 40 50
ความแตกต่าง Compile-time vs Runtime
| ประเภท | ค่าคงที่ | ค่าเปลี่ยนได้ |
|---|---|---|
| Compile-time | คงที่ตลอดการรัน | ไม่ได้ |
| Runtime | ไม่ได้ | ผู้ใช้ป้อนได้ต่างกันทุกรอบ |
ตัวอย่างที่ 3: Array Initialization แบบต่างๆ
#include <stdio.h>
int main() {
int a[4]; // ไม่ initialize -> garbage
int b[4] = {1}; // b[0]=1, b[1..3]=0
int c[4] = {1,2,3,4}; // initialize ทั้งหมด
int i;
printf("Array a (garbage):\\n");
for (i = 0; i < 4; i++) printf("a[%d]=%d\\n", i, a[i]);
printf("Array b (partial init):\\n");
for (i = 0; i < 4; i++) printf("b[%d]=%d\\n", i, b[i]);
printf("Array c (full init):\\n");
for (i = 0; i < 4; i++) printf("c[%d]=%d\\n", i, c[i]);
return 0;
}ผลลัพธ์ตัวอย่าง
Array a (garbage): a[0]=8 a[1]=0 a[2]=54 a[3]=0 Array b (partial init): b[0]=1 b[1]=0 b[2]=0 b[3]=0 Array c (full init): c[0]=1 c[1]=2 c[2]=3 c[3]=4
กฎสำคัญ: Partial initialization -> element ที่เหลือจะเป็น 0 อัตโนมัติ
ข้อควรระวัง
- Index เริ่มที่ 0 จบที่ size-1
- Out-of-bounds access = Undefined Behavior
- Array name = address ของ element แรก (decay to pointer)
- sizeof(array) ให้ขนาดทั้งหมด (bytes) ไม่ใช่จำนวน element