Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

อาร์เรย์ (Arrays) ในภาษา C

อาร์เรย์คือการรวบรวมข้อมูลชนิดเดียวกันไว้ในหน่วยความจำที่ติดกัน ตำแหน่งแรกคือดัชนี 0 และตำแหน่งสุดท้ายคือขนาดลบ 1

รูปแบบไวยากรณ์

type array_name[array_size];

การกำหนดค่าเริ่มต้น

type array_name[array_size] = { elements of array };

ตัวอย่าง

#include <stdio.h>
int main() {
    int a[5];
    int i, j;
    for (i = 0; i < 5; i++) {
        a[i] = i + 100;
    }
    for (j = 0; j < 5; j++) {
        printf("Element[%d] = %d\n", j, a[j]);
    }
    return 0;
}

ผลลัพธ์

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104