C指针,指向指针,赛格故障 [英] C pointer pointer, and seg fault

查看:112
本文介绍了C指针,指向指针,赛格故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我C.简单的链表我的问题是headRef = newNode;这将导致分段错误。然后我试图代替* headRef = newNode;它解决了赛格故障问题。虽然code的两条线在我看来,以相同的方式工作,所以是一款引起赛格故障,另外一个呢?
先谢谢了。

 结构节点{
  int数据;
  结构节点*接下来的;
};无效推送(结构节点** headRef,int数据){
  结构节点* newNode =的malloc(sizeof的(结构节点));
  如果(newNode!)回报;
  newNode->数据=数据;
  newNode->接下来= * headRef;
  headRef =安培; newNode;
  返回;
}


解决方案

newNode 已经是一个地址,你已经宣布它作为一个指针:结构节点* newNode 。随着 * headRef = newNode 你指定的地址,类似的指针,一个结构节点* 结构节点*

的困惑是, headRef =安培; newNode 出现的 的是同样有效的,因为类型同意:你分配给一个结构节点** 另一个结构节点**

但是,这是错误的,原因有二:


  1. 您想改变你的函数参数 headRef ,一个结构节点* 的价值。你已经通过的地址 headRef 进入功能,因为C是通过按值,所以要改变一个变量,你需要它地址。要更改的这个变量是地址,所以你传递一个指针的指针,一个结构节点** :附加水平间接是必要的,这样可以改变函数中的地址,有一个变化反映的 outide 的功能。所以,在函数中,你需要的解引用的变量来获得你想要改变什么:在你的函数,你想改变 * headRef 不可以 headRef

  2. newNode 正在创造一个间接的不必要的水平地址。要分配,如上面提到的价值,是该地址的 newNode 不可以地址<举行挖一挖> 的 newNode

Below is my simple linked list in C. My question is in "headRef = &newNode;" which causes segmentation fault. Then I tried instead "*headRef = newNode;" which resolves the seg fault problem. Though the two lines of code seem to me to work in the same way, why is one causing seg fault and the other one not? Thanks in advance.

struct node{
  int data;
  struct node* next;
};

void Push(struct node** headRef, int data){
  struct node* newNode = malloc(sizeof(struct node));
  if(!newNode) return;
  newNode->data = data;
  newNode->next = *headRef;
  headRef = &newNode;
  return;
}

解决方案

newNode is already an address, you've declared it as a pointer: struct node *newNode. With *headRef = newNode you're assigning that address to a similar pointer, a struct node * to a struct node *.

The confusion is that headRef = &newNode appears to be similarly valid, since the types agree: you're assigning to a struct node ** another struct node **.

But this is wrong for two reasons:

  1. You want to change the value of your function argument headRef, a struct node *. You've passed the address of headRef into the function because C is pass-by-value, so to change a variable you'll need it's address. This variable that you want to change is an address, and so you pass a pointer to a pointer, a struct node **: that additional level of indirection is necessary so that you can change the address within the function, and have that change reflected outide the function. And so within the function you need to dereference the variable to get at what you want to change: in your function, you want to change *headRef, not headRef.
  2. Taking the address of newNode is creating an unnecessary level of indirection. The value that you want to assign, as mentioned above, is the address held by newNode, not the address of newNode.

这篇关于C指针,指向指针,赛格故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆