简体   繁体   English

如果使用空值初始化的结构占用空间

[英]If an struct initialized with null values takes up space

I am not too familiar with C, but I am wondering how structs are constructed in memory. 我对C不太熟悉,但是我想知道如何在内存中构造结构。 Take for example this struct : 这个结构为例:

struct Books {
  char  title[50];
  char  author[50];
  char  subject[100];
  int   book_id;
};

int main() {
  struct Books Book1;
  struct Books Book2;
}

I'm wondering if you just initialize it like struct Books Book1; 我想知道您是否像struct Books Book1;一样初始化它struct Books Book1; , if it will allocate memory for all the fields it has ( title , author , etc.). ,如果它将为其拥有的所有字段( titleauthor等)分配内存。 If not, wondering what it does. 如果没有,想知道它会做什么。 I'm wondering how a programming language compiles a struct when the fields are null or not initialized. 我想知道当字段为null或未初始化时,编程语言如何编译结构。

If it is empty/blank/allocates no memory, then say you set it to this: 如果为空/空白/不分配内存,则说您将其设置为此:

strcpy(Book1.title, "C Programming");

And then you unset it. 然后您取消设置。 Wondering if it clears the memory so it goes back to zero, or it keeps the memory allocated. 想知道是否清除内存,使其恢复为零,还是保持已分配的内存。

struct Books Book1; is a variable declaration, not an initialization. 是变量声明,而不是初始化。 All variable declarations allocate memory for the variable, there's nothing different about struct declarations. 所有变量声明都为变量分配内存,而struct声明没有什么不同。 The amount of memory allocated is sizeof(struct Books) . 分配的内存量为sizeof(struct Books)

If the variable is not initialized, it allocates memory, but the initial contents of the memory are implementation-dependent (unless it's a static variable, then it's as if every field were initialized to 0 ). 如果未初始化变量,则分配内存,但是内存的初始内容取决于实现(除非它是静态变量,则好像每个字段都初始化为0 )。

Global variables are allocated when the program starts; 程序启动时分配全局变量; since they're also static, they will get default zero initialization if there's no initializer provided. 由于它们也是静态的,因此如果没有提供初始化程序,它们将默认为零初始化。

Local variables are allocated when the function or block is entered, and the memory allocation stays until the function or block is exited. 输入功能或块时,将分配局部变量,并且内存分配将一直保留到退出功能或块为止。

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

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