我正在嘗試使用 c 學習影像處理。
#include <stdio.h>
int main(){
FILE *streamIn;
streamIn=fopen("lena512.bmp","r");
//read imageHeader and colorTable
unsigned char header[54];//to store the image header
//unsigned char colorTable[1024];//to store the colorTable,if it exists
for(int i=0;i<54;i ){
header[i]=getc(streamIn);
}
/*
width of the image(18th byte)
height of the image(22nd byte)
bitDepth of the image(28th byte)
*/
int width=*(int*)(&header[18]);
int height=*(int*)(&header[22]);
int bitDepth=*(int*)(&header[28]);
}
我遇到了我無法理解的線。
int width=*(int*)(&header[18]);
為什么我們不能簡單地進行型別轉換 int width=(int)(header[18]);?
uj5u.com熱心網友回復:
我遇到了我無法理解的線。
int width=*(int*)(&header[18]);
撰寫它的人也沒有,因為這在幾個不同的方面都是明顯的未定義行為。它給出了這給出了一個未對齊的地址(在主流系統上)以及嚴格的別名違規。什么是嚴格的別名規則?
最后的那 3 行是錯誤,你不能像那樣寫 C 代碼。撰寫此程式的正確方法可能是將資料復制到 OS API 提供的預定義結構中。
uj5u.com熱心網友回復:
您正在使用*(int*)(&header[18]),您想知道為什么(int)(header[18])不能使用。
嗯,這些是完全不同的表達方式。
第一個取地址的header[18],這是一個unsigned char,所以這給出了一個指標此。將其int強制轉換為指向并*在賦值中取消參考它的指標會復制int從該地址開始的完整地址,讀取所有必需的位元組。
第二個簡單地讀取單個unsigned char輸入header[18]并將值轉換為 an int。這將僅使用第一個位元組。
注意:微軟的頭檔案提供了 BMP 頭的結構定義。使用它們要好得多。例如,您可以呼叫fread()讀取標題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322577.html
下一篇:為什么С忽略if陳述句?
