代碼片段:
struct student *q[13];
struct student h[13] = { ... };
for (i = 0; i < 13; i++)
*q[i] = h[i]; // 此處報:寫入位置 0xCCCCCCCC 時發生訪問沖突
q 是指針數組,每個元素是未初始化的野指針(調試模式下為 0xCCCCCCCC)。*q[i] = h[i] 試圖通過野指針寫入內存,導致訪問違規。將指針指向已存在的結構體實例:
for (i = 0; i < 13; i++)
q[i] = &h[i]; // 取地址賦值給指針
之後通過 q[i]->grade 或 (*q[i]).grade 訪問成員即可。
q[i] = (struct student*)malloc(sizeof(struct student)) 並拷貝數據。swap 中交換的是指針,不移動結構體本身,效率更高。