C结构的指针初始化

C结构的指针初始化

本文介绍了C结构的指针初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当包含结构指针数组的结构体实例化,
我保证,在结构数组成员的所有指针将被设置为 NULL

When a struct that contains an array of struct pointers is instantiated,am I guaranteed that all pointers in the struct array member will be set to NULL?

下面是一个例子结构:

typedef struct mmNode {
  int val;
  int board[2][NUM_PITS+1];
  int side;
  struct mmNode* children[NUM_PITS+1];
} mmNode;

IE:如果我创建mmNode结构的实例,将 mmNode.children 的元素总是被设置为 NULL

推荐答案

这取决于你如何初始化你的结构。

It depends how you initialise your struct.

mmNode a;                              // Everything default-initialized

void foo()
{
    static mmNode b;                   // Everything default-initialized

    mmNode  c;                         // Nothing initialized
    mmNode  d = { 0 };                 // Everything default-initialized
    mmNode *p = malloc(sizeof(*p));    // Nothing initialized
    mmNode *q = calloc(1, sizeof(*q)); // Everything zero-initialized
}

没有初始化意味着所有成员都将只是随机的垃圾值。 默认初始化意味着所有成员将被初始化为0,这对于指针成员将等同于 NULL 。 零初始化意味着一切都将被设置,位为0。这只能在平台上,其中 NULL 重新按位0 psented $ P $工作。

"Nothing initialized" means that all members will just have random junk values. "Default-initialized" means that all members will be initialized to 0, which for pointer members will be equivalent to NULL. "Zero-initialized" means that everything will be set, bitwise, to 0. This will only work on platforms where NULL is represented with bitwise 0.

这篇关于C结构的指针初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 03:11