当我想为一个结构声明新成员时,有些麻烦我不明白

When I want to declare new members for a Struct,some trouble I don't understand

我像下面这样初始化一个结构成员:

struct MyStruct {

  int member_a;

};
int main(){

MyStruct s;//method 1

MyStruct * ps;//method 2

return 0;
}

方法一和方法二有什么区别?为什么有人用方法一有人用方法二?

你的结构只有一个成员,你以后不要添加任何其他成员,你不能在结构之外这样做。

看我的例子:

// Example 1
// Referencing a structure member locally in "main()" with the "dot operator"

#include <stdio.h>

struct Test // unique definition of the struct
{
    int x;
};

int main(void)
{
    struct Test sTest; // we create an instance of the struct

    sTest.x = 2;       // we assign a value to the member of the struct

    printf("x = %d\n",sTest.x);

    return 0;
}

所以,当你这样做时:

MyStruct s;//method 1

MyStruct * ps;//method 2

你真的这样做了:

MyStruct s;

您说要创建类型为 MyStruct 的结构,称为 s。会为其分配内存,但不会手动初始化其成员,这一点你可能要记住!

然后这个

MyStruct * ps;

创建一个指向您的结构的指针,称为 ps。这意味着,ps 已准备好 指向 类型为 MyStruct 的结构。它是指向结构的 POINTER,而不是结构。

我的示例来源是 here


正如 cris 所指出的,一本书(参见 SO here 的相关列表)可能是你所需要的,因为你的 post 中有很多混乱。在线教程也很好。

另请注意,C 和 C++ 是两种不同的编程语言。

您应该使用方法 1,因为方法 2 没有声明 MyStruct 类型的变量,它声明了一个指针(指向 MyStruct 类型的变量)。

我一般用method_2。在像二叉树这样的数据结构中,如果我有一个指向 struct_node 的指针,比如 temp_pointer,现在我需要将其更改为它的 left_child,我可以简单地将指针指向left_child。现在,如果我需要更改 left_child 中的某些值,我可以简单地更改 temp_pointer 指向的节点中的值。 method_1 不可能做到这一点。在那里,我们将有一个 left_child 的单独副本,而不是指向 left_child 的指针(一个单独的副本将具有相同的值,但地址不同)。 method_1 不会更改原始节点(即 left_child)中的值,而只会更改副本中的值。

此外,假设我们有一个 mystruct_pointer 和另一个 temp_pointer。我们可以比较两者(mystruct_pointer == temp_pointer),并检查它们是否指向同一个节点。 method_1.

不可能做到这一点

记住,这个 method_2 只声明了一个指向 mystruct 类型的指针。要实际创建 mystruct 类型,您必须使用 malloc 或 calloc 分配内存。