gpt4 book ai didi

c - 全局指针导致段错误?

转载 作者:太空狗 更新时间:2023-10-29 15:14:31 25 4
gpt4 key购买 nike

用gcc编译然后运行时,代码

    int *p;    int main() {*p = 1;}

导致段错误。

显然,内存位置无法写入 p 中包含的内容。

为什么????

另一方面,

    int q[];    int main() {*q = 1;}

运行良好。

这是怎么回事??

为什么p只包含只读内存?

最佳答案

第一个例子有一个野指针(未显式初始化)。由于它不是一个自动变量,它被设置为 0,这显然不是你拥有的内存。你可以通过打印出来看到它:

printf("%p\n", p)

至于第二个,C99 §6.9.2 实际上给出了这个例子:

EXAMPLE 2 If at the end of the translation unit containing

int i[];

the array i still has incomplete type, the implicit initializer causes it to have one element, which is set to zero on program startup.

一般情况下,具有暂定定义(无初始化器)的对象初始化为 0,这对于数组意味着元素值为 0 的 1 元素数组。

关于c - 全局指针导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3225016/

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