【发布时间】:2020-10-20 08:55:20
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* link;
};
struct Node* A;
int main(){
struct Node* temp = (struct Node*)malloc(sizeof(Node));
temp->data = 2;
temp->link = NULL;
A = temp; // in this line i have doubt
return 0;
}
怀疑是: A 和 temp 都是指向节点的指针。 A = temp 可以有两种含义:
- 我们正在复制 A 中 temp 的地址,因此 A 将指向同一个地址。(意味着它们都是相同的标识/变量)
- 我们正在复制 temp 的元素并将其分配给 A 的元素。(意味着它们都是单独的标识/变量)。我们通常在结构中这样做。
所以请帮助我理解它。
【问题讨论】:
-
您从未为
temp分配任何内存。temp->data = NULL应该是temp->link = NULL。 -
temp 是指针,不是结构体,所以 temp->data = 2;无效 - 您分配给尚未分配的内存。您需要声明“节点温度;”在堆栈上分配它,或者使用 new() 分配一个实例。相关:stackoverflow.com/questions/9397288/…
-
如果你为 temp 或 A 分配了内存,或者为它们分配了某个变量的地址,那么它们都指向同一个地址。
-
@Barmar 是的,但我在问别的问题,请检查描述。我知道这个话题不清楚,但我不能把这个问题全放在这个话题上。
-
@Corbell 是的,你的意思是我需要先使用 malloc 为其分配内存。是的,这是我犯的错误之一,但我在问别的问题,请阅读描述以了解我的要求。顺便谢谢。