2016-01-12 259 views
-1
#include<stdio.h> 
#include<stdlib.h> 
struct test 
{ 
    int data; 
    struct test *next; 
}; 
void main() 
{ 

    struct test *head=(struct test *)malloc(sizeof(struct test)); 
    struct test **ref=&head; 

    head->data=5; 
    head->next=NULL; 
    printf("\n %d \n %d",head->data,head->next); 
    printf("\n %d \n %d",**ref->data,**ref->next); 



} 

说明:C指针双指针

我已经试过上述一段代码。

是不是**ref是否与*head相同?如果不是为什么?

此外,编译器在第二printf引发错误说datanext不是structureunion的一部分。

+1

欢迎来到Stack Overflow! [请参阅此讨论,为什么不在'C'中投射'malloc()'和family的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+1

没有任何编程方面,如果'** ref与* head'相同,那么为什么你认为额外的'*'在那里呢? –

+0

换句话说,在你的'printf(“\ n%d \ n%p”,(* ref) - > data,(* ref) - > next)版本中有''''和'您需要将圆括号内的指针包围起来,才能应用正确的运算符优先级。 –

回答

3

你有两个错误,一个语法(当你使用点符号时使用箭头符号),另一个与operator precedence有关。

选择运算符->.比取消引用运算符*具有更高的优先级。这意味着表达式**ref->data等于**(ref->data)。这当然是无稽之谈,不会构建为data不是一个指针。

你有两个选择:

  1. 使用例如(*ref)->data
  2. 使用例如(**ref).data

我会选择去1作为ref“参考”一指针的结构,即语法更内嵌你做什么,IMO。


在一个不相关的音符,你不应该打印指针时,你应该使用"%p"使用"%d"格式。见例如this printf (and family) reference

1

**ref是指向指向struct test的指针,*head是指向struct test的指针。

误差是存在的,因为whene参考,**refstruct test类型的,你应该使用点.去的结构的成员:

(**ref).data 

head是一个指向struct test,和您可以在那里正确使用->运算符。