简体   繁体   English

未初始化时,结构中的值是什么?

[英]What are the values in a struct when uninitialized?

Let's say I have a struct: 假设我有一个结构:

typedef struct{
   int a;
   float b;
} stuff;

If I have code like: 如果我有类似的代码:

stuff myStuff;
printf( "%d", myStuff.a ) ;

What would I get? 我会得到什么? Would the field always be initialized to 0? 是否总是将字段初始化为0?

In C11, any struct members that are not explicitly initialized (as is the case for you) have indeterminate values. 在C11中,任何未显式初始化的结构成员(如您的情况)都具有不确定的值。 C11 6.7.9/10: C11 6.7.9 / 10:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. 如果未自动初始化具有自动存储期限的对象,则其值不确定。

Reading such an indeterminate value produces undefined behaviour. 读取这样一个不确定的值会产生不确定的行为。 C11 6.3.2.1/2: C11 6.3.2.1/2:

If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined. 如果左值指定了可以使用register存储类声明的自动存储持续时间的对象(从未使用其地址),并且该对象未初始化(未使用初始化器声明,并且在使用前未对其进行任何赋值) ),则行为未定义。

Finally, Annex J.2 (Undefined behavior) clarifies this: 最后,附件J.2(未定义的行为)对此进行了澄清:

The behavior is undefined in the following circumstances: 在以下情况下,行为是不确定的:

  • The value of an object with automatic storage duration is used while it is indeterminate (6.2.4, 6.7.9, 6.8). 具有自动存储期限的对象的值在不确定时使用(6.2.4、6.7.9、6.8)。

No. The field could have any value at all. 否。该字段可以有任何值。 Doing something like this is considered a bug since the value is not predictable. 这样做是错误的,因为该值是不可预测的。

It depends on whether an object of the structure has the static storage duration or it is a local object. 这取决于结构的对象是具有静态存储持续时间还是它是本地对象。 If an object of the structure has the static storage duration when all its data members will be initialized by zeroes. 如果结构的对象具有静态存储持续时间,则将其所有数据成员初始化为零。 otherwise the object will not be initialized. 否则,该对象将不会初始化。

For example 例如

#include <stdio.h>

typedef struct
{
    int a;
    float b;
} stuff;

stuff s1; // initialized by zeroes

int main( void )
{
    stuff s2;     //indetermined values

    printf( "%d\n", s1.a ) ;  // 0 will be outputed
    printf( "%d\n", s2.a ) ;  // any value can be outputed
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM