簡體   English   中英

如何在不創建變量或指針或不使用數據類型的 sizeof 的情況下找到數據類型的大小?

[英]How can you find the size of a datatype without creating a variable or pointer, or using sizeof of the datatype?

下面顯示的問題是一個面試問題:

Q)你被賦予/有一個數據類型,比如 C 中的 X。

要求是獲取數據類型的大小,而不聲明該類型的變量或指針變量,

當然,不使用 sizeof 運算符!

我不確定是否已經在 SO 上問過這個問題。

感謝並問候麥迪

定義 sizeof_type( type ) (size_t)((type*)1000 + 1 )-(size_t)((type*)1000)

原文來自這個討論。 http://www.linuxquestions.org/questions/programming-9/how-to-know-the-size-of-the-variable-without-using-sizeof-469920/

這應該可以解決問題:

#include <stdio.h>

typedef struct
{
   int i;
   short j;
   char c[5];

} X;

int main(void)
{
   size_t size = (size_t)(((X*)0) + 1);
   printf("%lu", (unsigned long)size);

   return 0;
}

size_t size = (size_t)(((X*)0) + 1);解釋size_t size = (size_t)(((X*)0) + 1);

  • 由於對齊,假設sizeof(X)將返回 12 ( 0x0c )
  • ((X*)0)使X類型的指針指向內存位置 0 ( 0x00000000)
  • + 1將指針增加一個X類型元素的大小,因此指向0x0000000c
  • 表達式(size_t)()將表達式(((X*)0) + 1)給出的地址轉換回整數類型 ( size_t )

希望能提供一些見解。

聲明一個具有該類型成員的結構,然后使用 offsetof 來計算大小?

struct outer
{
     X x;
     char after;
};

offsetof(outer, after)應該給你 x 的(對齊的)大小。 請注意,我本身並沒有聲明該類型的變量,也沒有聲明指向該類型的指針,而是將它作為結構聲明的成員包含在內,在該結構聲明中我測量了它之后的成員的位置。

offsetof 宏可以定義為

#define offsetof(S, f) ((size_t)(&((S *)0)->f))

您可以將 0(或任何任意值)類型轉換為數據類型 X* 以查找數據類型的大小,就像下面的示例:

    #include <stdio.h>

    struct node{
        char c;
        int i;
    };

    int main()
    {
        printf("Sizeof node is: %d\n", ((char *)((struct node *)0 + 1) - (char *)((struct node *)0)));   
// substract 2 consecutive locations starting from 0 that point to type node, 
//typecast these values to char * to give the value in number of bytes.
        return 0;
    }
printf("%d",(int)(&x+1)-(int)&x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM