简体   繁体   English

动态查找结构的大小

[英]Finding the size of the structure dynamically

Is there any way to find the structure size dynamically in C?? 有没有办法在C中动态查找结构大小?

Sizeof is compile time operator.. so what's the other option. Sizeof是编译时间运算符..那么另一个选择是什么。

If we can have dynamically allocated array(flexible arrays) in a structure, then finding the structure size dynamically should also be there.. Plz help me out... 如果我们可以在结构中动态分配数组(柔性数组),那么动态查找结构的大小也应该存在。.请帮助我...

当您在C中动态分配数组时,如果您想知道数组的大小,还必须记住它的大小!

Structure sizes must be known at compile-time. 结构大小必须在编译时知道。

If it contains a pointer to dynamically allocated memory then that memory is not part of the struct - it's outside the struct and the pointer is pointing at it - so it does not affect the sizeof the struct. 如果它包含指向动态分配的内存的指针,则该内存不属于该结构的一部分-它位于结构外部,并且指针指向该结构-因此它不会影响该结构的sizeof

If you're talking about flexible array member then you will need to implement your own way of knowing how much memory you allocated, eg have a struct member variable that holds the size. 如果您在谈论灵活数组成员,那么您将需要实现自己的方式来了解分配的内存量,例如,拥有一个持有大小的struct成员变量。

sizeof 's results are compile time constant as a the size of a variable or structure does not change during run-time. sizeof的结果是编译时常数,因为变量或结构的大小在运行时不会改变。

The only exception to this are V(ariable)L(ength)Arrays for which the code defnding them "knows" the size. 唯一的例外是V(ariable)L(ength)Array,为其定义代码的代码“知道”大小。

Referring: 引用:

we can have dynamically allocated array in a structure 我们可以在结构中动态分配数组

So let's assume: 因此,我们假设:

struct s
{
  size_t size;
  int * ints;
}

The size is sizeof(struct s) . 大小为sizeof(struct s) That is the sum of 那是

  • the size of an unsigned interger: sizeof(size_t) 无符号整数的大小: sizeof(size_t)
  • the size of a pointer to int : sizeof (int *) 指向int的指针的大小: sizeof (int *)
  • some optional padding bytes 一些可选的填充字节

This is independed of to how many bytes the structure's member int * ints may point. 这与结构的成员int * ints可以指向多少字节无关。

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

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