gpt4 book ai didi

c - 当我使用 int array[10] = {0}; 初始化时,数组存储在哪里?

转载 作者:行者123 更新时间:2023-11-30 18:50:34 25 4
gpt4 key购买 nike

默认情况下,本地数组存储在堆栈中。未初始化的本地数组将被分配垃圾值。但为什么这个语法 int array[10] = {0};默认情况下将所有数组元素初始化为零?即使我给int array[10] = {10, 20}; //It initialises all rest of the elements to zero.

在这种情况下它不是存储在堆栈中吗?它如何将它们全部初始化为零?

最佳答案

局部数组是否初始化与是否入栈无关。

如果实现使用堆栈,则数组将位于堆栈上,无论是否已初始化。

摘自 C standard 的第 6.7.9 节:

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If anobject that has static or thread storage duration is notinitialized explicitly, then:

— if it has pointer type, it isinitialized to a null pointer;

— if it has arithmetic type, it isinitialized to (positive or unsigned) zero;

— if it is an aggregate,every member is initialized (recursively) according to these rules,and any padding is initialized to zero bits;

— if it is a union, thefirst named member is initialized (recursively) according to theserules, and any padding is initialized to zero bits;

...

21 If there are fewer initializers in a brace-enclosed list than thereare elements or members of an aggregate, or fewer characters in astring literal used to initialize an array of known size than thereare elements in the array, the remainder of the aggregateshall be initialized implicitly the same as objects that have staticstorage duration.

因此,如果初始值设定项列表的元素少于数组,则剩余元素的初始化方式与非局部变量相同,即设置为 0。

关于c - 当我使用 int array[10] = {0}; 初始化时,数组存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39881490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com