Implementation-defined (2)
implementation-defined อีกเรื่องคือ alignment of members of structure ครับ

เวลาที่เรา declare structure ตัวอย่างเช่น
struct x { char a; int b; long c; };

การเรียงตัวของข้อมูลใน memory ของ structure นี้จะเป็น
|a|pad|b|pad|c|pad|

a, b, c คือค่าของ member ทั้งสาม
ส่วน pad คือช่องว่างครับ ซึ่งอาจจะมีหรือไม่มีก็ได้

pad แต่ละตัวอาจมีขนาดไม่เท่ากันก็ได้
pad ที่อยู่หลัง member แต่ละตัวมีขึ้นเพื่อให้ member ตัวถัดไป align อยู่บน memory boundary ที่เหมาะสม
ส่วน pad ตัวสุดท้ายจะ align ขนาดของ structure
ซึ่งทำให้เวลาที่มี array ของ structure จุดเริ่มต้นของ structure แต่ละตัวจะถูก align ไปด้วย

ทำไมต้องมีการทำ alignment ด้วย

ก็เพราะว่าการ access memory ที่อยู่บน boundary ที่เหมาะสมจะทำได้เร็วกว่า
อันนี้ขึ้นกับ platform ครับ
standard C เลยกำหนดให้ compiler เป็นผู้เลือกว่าจะ alignment ยังไง
มาดูตัวอย่างว่า compiler แต่ละตัวทำ alignment ยังไง

จากรูปจะเป็น alignment ของ C compiler ของ sun

จะเห็นได้ว่าบน CPU SPARC (sun) กับ x86 (intel) จะมี alignment ไม่เหมือนกัน

ส่วน Visual C ของ Microsoft สามารถกำหนดใน Project Settings หรือ comand line option ว่าจะให้ทำ alignment แบบไหน




Create Date : 23 สิงหาคม 2551
Last Update : 23 สิงหาคม 2551 18:53:31 น.
Counter : 657 Pageviews.

1 comments
  
บทความดีมากเลยครับ ขอบคุณมากครับ
โดย: ไอซ์ IP: 58.137.97.178 วันที่: 3 ตุลาคม 2551 เวลา:9:59:06 น.
ชื่อ :
Comment :
 *ใช้ code html ตกแต่งข้อความได้เฉพาะสมาชิก
 

Zkaru.BlogGang.com

zkaru
Location :
กรุงเทพฯ  Thailand

[ดู Profile ทั้งหมด]
 ผู้ติดตามบล็อก : 2 คน [?]