如何数组由编译器初始化(零)用C? [英] How are arrays initialised (to zero) in C by the compiler?

查看:167
本文介绍了如何数组由编译器初始化(零)用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我可能误会了数组如何创建,分配和初始化。如果是这样,请尝试字里行间。

Disclaimer: I might have misunderstood how arrays are created, allocated and initialised. If so, please try to read between the lines.

如果我创建做一个数组

int array[15] = {0};

中的所有元素阵列编译器会初始化元素 0 。这是如何由编译器完成?该编译器插入一个循环,迭代分配的内存,并设置每个元素为零?大小是否影响性能?即确实需要花费更长的时间来初始化双尺寸(30)的阵列?还要多久?双?对数? 2电源?

All elements of array the compiler will initialise the elements to 0. How is this done by the compiler? Does the compiler insert a loop that iterates the allocated memory and sets each element to zero? Does size impact performance? I.e. does it takes longer time to initialise an array of double size (30)? How much longer? Double? Logarithmic? Power of 2?

只是要求出于好奇。

推荐答案

我想,你说的是全局变量/数组。

I assume, you are talking about global variables/arrays.

其实,它不是编译器的任务(如果我们谈论现代操作系统)。编译器只是标记为初始化为零的该对象。

Actually, it is not compiler task (if we are talking about modern OSes). Compiler just marks this object as zero-initialized.

然后,接头使该对象在节,这应该用零来初始化。在ELF此款被命名为的.bss 。一般,这部分有没有数据(因为只有零),但它具有大小

Then, linker puts this object in section, that should be initialized with zeros. In ELF this section is named .bss. Usually, this section has no data (because there are only zeroes), but it has size.

然后,当加载器加载程序到内存中,它知道,它应该零出属于的.bss 部分内存。

And then, when loader loads your program into memory, it knows, that it should zero out memory that belongs to .bss section.

如果我们在谈论基于堆栈的(局部)变量,那么编译器只是调用 memset的()

If we are talking about stack-based (local) variables, then compiler just calls memset()

这篇关于如何数组由编译器初始化(零)用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆