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

Structure ในภาษา C

Structure เป็น user-defined datatype รวมข้อมูลประเภทต่างๆ เป็นชนิดเดียว มีสมาชิกหลายตัว ใช้ keyword struct เข้าถึงสมาชิกด้วย dot (.) operator

ไวยากรณ์

struct structure_name {
    member definition;
} structure_variables;

ตัวอย่าง

#include <stdio.h>
#include <string.h>

struct Data {
    int i;
    long int f;
} data, data1;

int main() {
    data.i = 28;
    printf("The value of i: %d\n", data.i);
    printf("Memory size occupied by data: %d\t%d", sizeof(data), sizeof(data1));
    return 0;
}

ผลลัพธ์

The value of i: 28
Memory size occupied by data: 16 16

Struct Data มี int (4 bytes) และ long int (8 bytes) รวม 16 bytes (อาจมี padding)