在 C 中,将结构分配给结构指针会分配结构的复制值吗?

In C, does assigning a struct to a struct pointer assigns a copied value of the struct?

我刚开始学习 C,如果命名不正确请见谅。

如果我将 struct 分配给 struct pointer 然后更改结构的值,当我尝试从 struct pointer.

访问值时它不会反映出来
struct Node_int *new_node_address = (struct Node_int *) malloc(sizeof(struct Node_int));
struct Node_int new_node_instance;
*new_node_address = new_node_instance;
new_node_instance.data = data;
new_node_instance.next= NULL;
printf("%d", new_node_address->data)

此处 printf("%d", new_node_address->data) 将 return 一个垃圾值,但以下代码中的相同打印语句将 return correct/assigned 数据。

struct Node_int *new_node_address = (struct Node_int *) malloc(sizeof(struct Node_int));
struct Node_int new_node_instance;
new_node_instance.data = data;
new_node_instance.next= NULL;
*new_node_address = new_node_instance;
printf("%d", new_node_address->data)

我想了解为什么会这样。 *new_node_address 是否获取内存中 new_node_instance 的复制值?

I want to understand why this is happening. Does *new_node_address gets the copied value of new_node_instance in the memory?

是的,有一个副本,解引用运算符*意味着你正在将数据复制到new_node_address指向的内存地址。哪个是malloc返回的内存块。

如果你想让指针指向声明的new_node_instance的地址,你需要:

new_node_address = &new_node_instance;

在这种情况下,不会发生任何复制,因此您也不需要分配内存,您正在使指针指向一个已经有内存存储的变量。

第二个代码片段之所以有效,是因为您是在分配数据后进行复制,而不是第一个代码片段。

初学者好像有错字

new_node_instance.data = data;
new_node_instance.data= NULL;

那是使用了相同的数据成员data。似乎第二个数据成员被命名为 nextlink.

If I assign a struct to a struct pointer and then change values of struct, it's not reflected when I try to access the value from struct pointer.

这是因为指针指向另一个动态分配的单独对象。

首先需要给对象赋值new_node_instance,然后将结构类型的对象赋值给动态分配的对象,例如

new_node_instance.data = data;
new_node_instance.next = NULL;

*new_node_address = new_node_instance;

struct Node_int new_node_instance = { .data = data, .next = NULL };
*new_node_address = new_node_instance;

也就是在赋值给结构类型的对象时复制数据成员的值。