在不使用sizeof的情况下查找大小

时间:2015-01-01 00:17:11

标签: 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中,是否可以找到struct的大小而无需使用sizeof

4 个答案:

答案 0 :(得分:10)

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

#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;
};

答案 1 :(得分:5)

是的,我们可以在不使用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);

答案 2 :(得分:-1)

总之,你不能。有些人建议使用指针算法,就像你在答案中所做的那样,以及使用宏来制作“sizeof运算符”。原因是数据类型的大小仅由机器的编译器知道。您的指针算术使用sizeof运算符,“在幕后”。

答案 3 :(得分:-1)

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

然后你可以选择使用它们。

然后,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强迫它成为现实。

相关问题