C语言 在不使用 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的大小?

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

#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=%ldn", (long)((void*)(((struct foo*)(NULL))+1)-NULL));
  printf("syzeov  =%ldn", (long)SYZEOV(struct foo));
  printf("sizeof  =%ldn", (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真的使用了那么多空间吗?应该不会。

如果您执行以下操作:

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来强迫它是真的。

相关内容

最新更新