3

#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可以有两种含义:

  1. 我们在 A 中复制 temp 的地址,因此 A 将指向同一个地址。(意味着它们都是相同的标识/变量)
  2. 我们正在复制 temp 的元素并将其分配给 A 的元素。(意味着它们都是单独的标识/变量)。我们通常在结构中这样做。

所以请帮助我理解它。

4

2 回答 2

1

分配指针只是复制地址,而不是指针指向的内容。所以A = temp;使Atemp指向同一个地址。

如果要复制元素,则必须取消引用指针:*A = *temp;

于 2020-06-30T05:41:15.087 回答
1

第一件事第一对。您如何在temp->data = NULL;此处分配 Null 数据是int类型。

您的选项 1 是正确的。

而且您刚刚声明了结构指针变量但尚未初始化。

您的代码有一些我修复的错误。运行下面的代码,看到 A 和 temp 在A=temp;语句后具有相同的地址,这意味着它们都指向同一个东西。

#include <stdio.h>
#include <stdlib.h>

struct Node{
   int data;
   struct Node* link;
};  // you had forgot ';' here
struct Node* A;
int main(){
   struct Node *temp;
   temp=(struct Node*)malloc(sizeof(struct Node));  
   // this allocates memory and assign its address into temp structure pointer
   temp->data = 2;  
   temp->link = NULL; // here you was doing mistake
   A = temp; // in this line i have doubt
   printf(" Address of pointer A %p", A);
   printf("\n Address of pointer temp is %p",temp);

 return 0;
}

如果您还有任何疑问,请告诉我。

于 2020-06-30T06:16:38.320 回答