Linux sizeof 运算符的实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14171117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:12:27  来源:igfitidea点击:

implementation of sizeof operator

clinuxgccsizeoftypecast-operator

提问by Raghu Srikanth Reddy

I have tried implementing the sizeof operator.. I have done in this way..

我试过实现 sizeof 运算符..我已经这样做了..

#define my_sizeof(x) ((&x + 1) - &x)

But it always ended up in giving the result as '1' for either of the data type..

但对于任何一种数据类型,它总是以“1”作为结果。

I have then googled it for this.. and i found the code typecasted

然后我为此在谷歌上搜索了它..我发现代码类型转换

#define my_size(x) ((char *)(&x + 1) - (char *)&x)

And the code is working if it is typecasted.. I dont understand why.. This code is also PADDING a STRUCTURE perfectly..

如果它被类型转换,代码就可以工作..我不明白为什么..这段代码也完美地填充了结构..

It is also working for

它也适用于

#define my_sizeof(x) (unsigned int)(&x + 1) - (unsigned int)(&x)

Can anyone please explain how is it working if typecasted and if not typecasted?

任何人都可以解释一下如果类型转换它是如何工作的,如果没有类型转换它是如何工作的?

Thanks in advance..

提前致谢..

采纳答案by NPE

The result of pointer subtraction is in elementsand not in bytes. Thus the first expression evaluates to 1by definition.

指针减法的结果是元素而不是字节。因此,第一个表达式1根据定义计算为。

This aside, you really ought to use parentheses in macros:

除此之外,你真的应该在宏中使用括号:

#define my_sizeof(x) ((&x + 1) - &x)
#define my_sizeof(x) ((char *)(&x + 1) - (char *)&x)

Otherwise attempting to use my_sizeof()in an expression can lead to errors.

否则尝试my_sizeof()在表达式中使用会导致错误。

回答by Oliver Charlesworth

But it always ended up in giving the result as '1' for either of the data type

但它最终总是将任何一种数据类型的结果都设为“1”

Yes, that's how pointer arithmetic works. It works in units of the type being pointed to. So casting to char *works units of char, which is what you want.

是的,这就是指针算法的工作原理。它以所指向的类型为单位工作。所以投射到 的char *作品单位char,这就是你想要的。

回答by Basile Starynkevitch

The sizeofoperator is part of the C (and C++) language specification, and is implemented inside the compiler (the front-end). There is no way to implement it with other C constructs (unless you use GCC extensions like typeof) because it can accept either types or expressions as operand, without making any side-effect (e.g. sizeof((i>1)?i:(1/i))won't crash when i==0but your macro my_sizeofwould crash with a division by zero). See also C coding guidelines, and wikipedia.

sizeof操作符是C(和C ++)语言规范的一部分,并且编译器(前端)的内部来实现。没有办法用其他 C 结构来实现它(除非你使用像typeof这样的 GCC 扩展),因为它可以接受类型或表达式作为操作数,而不会产生任何副作用(例如sizeof((i>1)?i:(1/i))不会崩溃,i==0但你的宏my_sizeof会崩溃除以零)。另请参阅C 编码指南维基百科

You should understand C pointer arithmetic. See e.g. this question. Pointer difference is expressed in elements not bytes.

您应该了解 C指针算法。参见例如这个问题。指针差异以元素而非字节表示。

回答by user2311046

# define my_sizeof(x) ((&x + 1) - &x)

# 定义 my_sizeof(x) ((&x + 1) - &x)

&x gives the address of your variable and incrementing it with one (&x + 1), will give the address, where another variable of type x could be stored. Now if we do arithmetic over these addresses like ((&x + 1) - &x), then it will tell that within ((&x + 1) - &x) address range 1 variable of type x could be stored.

&x 给出变量的地址,并用 1 (&x + 1) 递增,将给出可以存储另一个 x 类型变量的地址。现在,如果我们对这些地址进行算术运算,例如 ((&x + 1) - &x),那么它会告诉在 ((&x + 1) - &x) 地址范围内可以存储 1 个类型为 x 的变量。

Now, if we typecast that amount of memory with (char *) [because size of char is 1 byte and incrementing a char * would move with one byte only], then we would get the number of bytes type x is consuming

现在,如果我们用 (char *) [因为 char 的大小是 1 个字节并且增加一个 char * 只会移动一个字节] 来对那个内存量进行类型转换,那么我们将得到类型 x 消耗的字节数

回答by Kuppappa DH

#define my_sizeof(x) ((char *)(&x + 1) - (char *)&x)
#define my_sizeof(x) ((char *)(&x + 1) - (char *)&x)

This my_sizeof()macro will not work in the following cases:

my_sizeof()宏在以下情况下不起作用:

  1. sizeof 1- 4 byte (for a platform with 4-byte int)
    my_sizeof(1)- won't compile at all.

  2. sizeof (int)- 4 byte(for a platform with 4-byte int)
    my_sizeof(int)- won't compile code at all.

  1. sizeof 1- 4 字节(对于具有 4 字节的平台int
    my_sizeof(1)- 根本无法编译。

  2. sizeof (int)- 4 字节(对于具有 4 字节的平台int
    my_sizeof(int)- 根本不会编译代码。

It will work only for variables. It won't work for data types like int, float, charetc., for literals like 2, 3.4, 'A', etc., nor for rvalue expressions like a+bor foo().

它仅适用于变量。它不会工作,为数据类型,例如intfloatchar等等,对于喜欢文字23.4'A',等,也不是右值表达式像a+bfoo()

回答by roottraveller

#define my_sizeof(x) ((&x + 1) - &x)

&xgives the address of the variable (lets say double x) declared in the program and incrementing it with 1 gives the address where the next variable of the type x can be stored (here addr_of(x) + 8, for the size of a double is 8Byte).

&x给出程序中声明的变量的地址(假设为 double x),并用 1 递增给出可以存储 x 类型的下一个变量的地址(此处addr_of(x) + 8,double 的大小为 8Byte)。

The difference gives the result that how many variables of type of xcan be stored in that amount of memory which will obviously be 1 for the type x (for incrementing it with 1 and taking the difference is what we've done).

差异给出的结果是,x在该内存量中可以存储多少类型的变量,对于类型 x 显然是 1(用 1 递增它并取差异是我们所做的)。

#define my_size(x) ((char *)(&x + 1) - (char *)&x)

typecasting it into char*and taking the difference will tell us how many variables of type charcan be stored in the given memory space (the difference). Since each charrequires only 1 Byte of memory therefore (amount of memory)/1 will give the number of bytes between two successive memory locations of the type of variable passed on to the macro and hence the amount of memory that the variable of type xrequires.

对其进行类型转换char*并采用差异将告诉我们char在给定的内存空间中可以存储多少类型的变量(差异)。由于每个char只需要 1 字节的内存,因此(内存量)/1 将给出传递给宏的变量类型的两个连续内存位置之间的字节数,以及类型变量所需的内存量x

But you won't be able to pass any literal to this macro and know their size.

但是您将无法将任何文字传递给这个宏并知道它们的大小。

回答by C.Y

I searched this yesterday, and I found this macro:

我昨天搜索了这个,我找到了这个宏:

#define mysizeof(X)  ((X*)0+1)

Which expands X only once (no error as double evaluation of expression like x++), and it works fine until now.

它只扩展 X 一次(像 x++ 这样的表达式的双重评估没有错误),并且直到现在它都可以正常工作。

回答by user3458845

#include<bits/stdc++.h>

using namespace std;
//#define mySizeOf(T) (char*)(&T + 1) - (char*)(&T)

        template<class T>
size_t mySizeOf(T)
{
        T temp1;
        return (char*)(&temp1 + 1) - (char*)(&temp1);
}
int main()
{
        int num = 5;
        long numl = 10;
        long long numll = 100;
        unsigned int num_un_sz = 500;

        cout<<"size of int="<<mySizeOf(num) << endl;
        cout<<"size of long="<<mySizeOf(numl) << endl;
        cout<<"size of long long ="<<mySizeOf(numll) << endl;
        cout<<"size of unsigned int="<<mySizeOf(num_un_sz) << endl;
        return 0;
}