【问题标题】:problem-related to structures and pointers in C与 C 中的结构和指针相关的问题
【发布时间】: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 可以有两种含义:

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

所以请帮助我理解它。

【问题讨论】:

  • 您从未为temp 分配任何内存。 temp-&gt;data = NULL 应该是 temp-&gt;link = NULL。
  • temp 是指针,不是结构体,所以 temp->data = 2;无效 - 您分配给尚未分配的内存。您需要声明“节点温度;”在堆栈上分配它,或者使用 new() 分配一个实例。相关:stackoverflow.com/questions/9397288/…
  • 如果你为 temp 或 A 分配了内存,或者为它们分配了某个变量的地址,那么它们都指向同一个地址。
  • @Barmar 是的,但我在问别的问题,请检查描述。我知道这个话题不清楚,但我不能把这个问题全放在这个话题上。
  • @Corbell 是的,你的意思是我需要先使用 malloc 为其分配内存。是的,这是我犯的错误之一,但我在问别的问题,请阅读描述以了解我的要求。顺便谢谢。

标签: c pointers struct


【解决方案1】:

首先要正确。如何在temp-&gt;data = NULL; 中分配 Null,这里的数据是 int 类型。

你的第一个选项是正确的。

而且你刚刚声明了结构指针变量但没有初始化。

您的代码有一些我已修复的错误。运行下面的代码,在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;
}

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

【讨论】:

  • 是的,我写的是 temp->data 而不是 temp-> 链接。真的很抱歉
  • 请检查代码 sn-p 并询问是否有任何疑问或您的答案仍然不清楚
  • 谢谢,我的疑惑即将消除。如果我现在声明一个新结构,例如 (temp1 = (struct Node*)malloc(sizeof(struct Node)); ) 如果我做 temp1 = temp 那么这意味着我在 temp1 中分配 temp 的地址还是我复制元素
  • 指针变量不同于普通变量。它们旨在指向相同类型的其他变量。这就是为什么您必须分配内存然后将其分配给此处的结构指针变量
  • 从技术上讲,指针保存它指向的对象的地址。但是printf 文字具有误导性。 A是一个指针,有一个地址。术语“指针 A 的地址”将是 &amp;A。
【解决方案2】:

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

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

【讨论】:

  • OP 的代码有足够多的未定义行为,忽略它会产生误导。从技术上讲,在 C++ 中,*A=*temp 不会复制上述代码中的任何内容,因为 (a) 上述程序的行为已经未指定,并且 (b) 没有一行 *A=*temp 不会导致未指定的行为.正确措辞具有挑战性,但除非您这样做,否则我认为此答案不正确并且对提问者有害。
  • stackoverflow.com/questions/4931123/… **Check this out ** in this they have used A=temp 复制元素。
  • @uditkumar11 因为那是结构变量,而不是指针。
猜你喜欢
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多