關於sizeof()使用的另外一種寫法—— sizeof * 變量

今天在閱讀代碼的時候再次遇到了sizeof()的另外一種使用方法,然後自己進行了嘗試,現在也僅僅是知道含義,深層次的含義此刻並不得而知,如果讀者您知道,希望您能評論一下,謝謝。

在readelf源碼中有get_64bit_section_headers()這樣一個函數,裏面在進行長度比較的時候有下面這樣的一段代碼:

Elf64_External_Shdr *  shdrs;
Elf_Internal_Shdr *    internal;
unsigned int           i;
unsigned int           size = filedata->file_header.e_shentsize;

if (size < sizeof * shdrs)
{
    if (! probe)
	error (_("The e_shentsize field in the ELF header is less than the size of an ELF section header\n"));
    return FALSE;
}

注意看if判斷,sizeof * shdrs, 這裏的sizeof可是sizeof()函數的意思,不是變量,shdrs是一個正經的指針。二者居然可以相乘,還沒有什麼問題!我是第一次見到這種寫法。我進行了嘗試也只是知道了它和什麼等價而已,至於爲什麼這樣,才疏學淺。網上也並沒有找到相關的文章。

sizeof * shdrs
sizeof(*shdrs)
sizeof(Elf64_External_Shdr)

上面這三種寫法結果是一樣的,都是計算Shdr指針指向的結構體Elf64_External_Shdr的大小。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章