繁体   English   中英

不使用sizeof查找尺寸

[英]Finding size without using sizeof

我了解我们可以使用以下方法找到某种类型的指针的大小:

printf("size of an int pointer: %d", sizeof(int*));
printf("size of a float pointer: %d", sizeof(float*));
printf("size of pointer to void: %d", sizeof(void*));

在C语言中,无需使用sizeof就能找到struct sizeof吗?

执行指针算术并测量步长。

#include <stdio.h>
struct foo { char a[5],b[98];};

#define SYZEOV(t) ((size_t)((void*)(((t*)(NULL))+1)-NULL))


int main(int m, char**n){
  printf("sizeexpr=%ld\n", (long)((void*)(((struct foo*)(NULL))+1)-NULL));
  printf("syzeov  =%ld\n", (long)SYZEOV(struct foo));
  printf("sizeof  =%ld\n", (long)sizeof(struct foo));
  return 0;
};

是的,我们可以执行以下操作来找到struct的大小,而无需使用sizeof

struct myStruct
{
   int a;
   int b;
}

struct myStruct s = {0, 0};

myStruct *structPointer = &s;
unsigned char *pointer1, *pointer2;
pointer1 = (unsigned char*) structPointer;
pointer2 = (unsigned char*) ++structPointer;

printf("%d", pointer2 - pointer1);

简而言之,你不能。 有人建议像使用答案一样使用指针算法,并建议使用宏来制作“ sizeof运算符”。 原因是数据类型的大小仅由机器的编译器知道。 您的指针算法是在后台使用sizeof运算符。

C的设计方式是sizeof总是返回指针增量(以字节为单位)以移至下一个数组元素,因此sizeof(type[N]) == N*sizeof(type)始终为true。

然后,您可以选择使用其中一种。

然后, sizeof或指针增量都不会真正返回操作数的大小,相反,当它们成为数组时,它们都将返回每个对象占用的内存量。

尝试类似:

struct myStruct
{
   double a;
   char b;
}

那么sizeof(struct myStruct)很可能是2*sizeof(double) ,而不是sizeof(double)+sizeof(char) ,因为制作myStruct数组myStruct一个数组元素必须相距那么远。

myStruct是否真的占用了那么多空间? 可能不是。

如果您执行以下操作:

struct myBigStruct
{
   struct myStruct small;
   char b;
}

那么sizeof(struct myBigStruct)仍然很可能是2*sizeof(double) ,而不是sizeof(struct myStruct)+sizeof(char)

所有这些都依赖于实现。

只是因为太多的人认为sizeof(type[N]) == N*sizeof(type)所以C通过这种方式使sizeof强制为真。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM