我可以在 C 中分配或返回具有未分配元素的结构吗?

问题描述 投票:0回答:1

在 C 中,使用未初始化的变量是未定义的行为。包括:

int x;
int y = x;

但是,假设我有以下内容:

struct Struct {
    int a;
    int b;
};
struct Struct s;
s.a = 1;
struct Struct s0 = s;
return s; // Assuming an enclosing function with the correct return type

在已分配部分(但不是全部)元素的情况下,上述代码是否会调用未定义的行为?

c struct initialization language-lawyer undefined-behavior
1个回答
0
投票

只要您不尝试访问统一的结构成员,就不存在未定义的行为。一旦您开始使用该未初始化的值,那么您就进入了 UB 领域。

© www.soinside.com 2019 - 2024. All rights reserved.