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

การประกาศ Structure ไม่มี Member ในภาษา C


โจทย์

ประกาศ Structure ไม่มี Member ได้ไหม? ถ้าได้ Size จะเป็นเท่าไหร่?

คำตอบ

ได้** ภาษา C อนุญาตให้ประกาศ Structure ว่าง (Empty Structure) และ Size จะเป็น **0 (Zero)** → เรียกว่า **Zero-size Structure**

ตัวอย่างโปรแกรม

#include <stdio.h>

// Structure ไม่มี Member
struct temp {
};

int main() {
    struct temp T; // ประกาศตัวแปร
    printf("Size of T: %zu\n", sizeof(T));
    return 0;
}

ผลลัพธ์:


Size of T: 0

อธิบาย

  • struct temp { }; ประกาศ Structure ชื่อ temp ไม่มี Member
  • struct temp T; ประกาศตัวแปร T
  • sizeof(T) คืนค่า **0**

ข้อควรระวัง (Caveats)

  • C++ ไม่รองรับ** Empty Struct (Size จะเป็น 1 ไบต์ เพื่อให้ Address Unique)
  • บาง Compiler (GCC) อนุญาตเป็น Extension แต่ Standard C ก็อนุญาต
  • ไม่สามารถ Deference Pointer ไปยัง Empty Struct ได้ (Undefined Behavior)
  • ไม่ควรใช้ในโค้ด Production จริง - ไม่มีประโยชน์ทางปฏิบัติ

การใช้งานจริง (Rare Cases)

  • Tag สำหรับ Type Safety (Opaque Pointer)
  • Placeholder ในโค้ดที่ Generate อัตโนมัติ
  • Alignment/Padding control ใน Struct ใหญ่