gpt4 book ai didi

c - 关于int *a={1,2,3}的有效性。为什么随后的 *a 会崩溃?

转载 作者:行者123 更新时间:2023-11-30 21:32:14 24 4
gpt4 key购买 nike

int main()
{
int *a={1,2,3}; //which value is stored and where it is stored
printf("\n%d",*a); //crashes here
}

请解释为什么上述崩溃。

最佳答案

发布的代码具有未定义的行为,因此它可以编译并执行,但结果是不可预测的。一种可能的结果是段错误。

行:

int *a={1,2,3};

尝试使用初始化列表初始化指向int的指针(其中包含太多元素;这应该生成警告),但此初始化列表是不是数组。

一种解决方案是使用实际的数组:

int arr[] = { 1, 2, 3 };
int *a = arr;

这里arr[]是一个不完整的数组类型。初始化列表用于初始化数组arr[],当到达初始化列表末尾时,数组类型完成。现在a是指向数组arr[]第一个元素的指针,其类型为int [3]

自 C99 起可用的另一个选项是使用复合文字:

int *a = (int []) { 1, 2, 3 };

这里,复合文字创建了一个匿名数组,a 指向该数组的第一个元素。请注意,在发布的代码中,该匿名数组将具有自动存储持续时间,也就是说,仅当程序在 main() 中执行时它才存在堵塞。一般来说,根据§6.5.2.5 5 of the C11 Draft Standard :

If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

关于c - 关于int *a={1,2,3}的有效性。为什么随后的 *a 会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48567426/

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