gpt4 book ai didi

c - 在 C 中引用未初始化的变量

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

如果我引用未初始化的变量,会发生什么?就像,

void func(int *p)
{
// My operation
}

int main()
{
int a;
func(&a);
}

最佳答案

What happens, If I reference uninitialized variable

func() 接收 main() 中定义的变量 a地址。在 func() 内部,由 func(int * pa) 定义的指针 pa 指向保存不确定的内存a 的值。

func() 可以通过执行

分配给 a
*pa = 42;

这会将 a 设置为 42

如果func()做了

int b  = *pa;

它读取未初始化内存,即a不确定值,这将调用 Undefined Behaviour .

来自 C11 标准(草案):

J.2 Undefined behavior

1 The behavior is undefined in the following circumstances:

[...]

  • The value of an object with automatic storage duration is used while it is indeterminate

关于c - 在 C 中引用未初始化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43291367/

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