易百教程

73、如何在不使用 sizeof 运算符的情况下在 c 中计算出结构体的大小?

方法一:

当增加指针时,指针会增加一块内存(内存块取决于指针数据类型),所以这里将使用这种技术来计算sizeof结构。

  • 首先,创建结构。
  • 创建一个指向结构的指针并分配 NULL 指针。
  • 将指针增加到 1。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
    char Name[12];
    int Age;
    float Weight;
    int RollNumber;
} sStudentInfo;
int main(int argc, char *argv[])
{
    //Create pointer to the structure
    sStudentInfo *psInfo  = NULL;
    //Increment the pointer
    psInfo++;
    printf("Size of structure  =  %u\n",psInfo);

    return 0;
}

输出结果如下:

Size of structure  =  24

方法二:

还可以使用指针减法计算结构的大小。使用指针减法可以计算两个指针之间的字节数。

  • 首先,创建结构。
  • 创建一个结构数组,这里是 aiData[2]
  • 创建指向结构的指针并分配数组的第一个和第二个元素的地址。
  • 减去指针以获得结构的大小。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
    char Name[12];
    int Age;
    float Weight;
    int RollNumber;
} sStudentInfo;
int main(int argc, char *argv[])
{
    //create an array of structure;
    sStudentInfo aiData[2] = {0};
    //Create two pointer to the integer
    sStudentInfo *piData1 = NULL;
    sStudentInfo *piData2 = NULL;
    int iSizeofStructure = 0;
    //Assign the address of array first element to the pointer
    piData1 = &aiData[0];
    //Assign the address of array third element to the pointer
    piData2 = &aiData[1];
    // Subtract the pointer
    iSizeofStructure = (char*)piData2 - (char *)piData1;
    printf("Size of structure  =  %d\n",iSizeofStructure);
    return 0;
}

运行上面示例代码,得到以下结果:

Size of structure  =  24