-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);



}

Explanation:

I've tried the above piece of code.

Isn't **ref same as *head? If not why?

Also the compiler is throwing an error at the second printf saying that data and next are not part of a structure or a union.

Jongware
  • 22,200
  • 8
  • 54
  • 100
vsag
  • 5
  • 2
  • 1
    Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Jan 12 '16 at 08:07
  • 1
    without any programming aspect, in case `**ref same as *head`, then why do you think that extra `*` is there, at all? – Sourav Ghosh Jan 12 '16 at 08:08
  • In other words, you have one too many `*` in your version of `printf("\n %d \n %p",(*ref)->data,(*ref)->next);` and you need to surround the pointer in parenthesis to have correct operator precedence apply. – David C. Rankin Jan 12 '16 at 08:37

2 Answers2

4

You have two errors, one syntactical (you use arrow notation when you should use dot notation), and the other has to do with operator precedence.

The selection operators -> and . have higher precedence than the dereference operator *. That means the expression **ref->data is equivalent to **(ref->data). This is of course nonsense and will not build as data is not a pointer.

You have two options:

  1. Use e.g. (*ref)->data
  2. Use e.g. (**ref).data.

I would go with option 1 as ref "references" a pointer to the structure, that syntax is more inline with what you do, IMO.


On an unrelated note, you should not use the "%d" format when printing pointers, you should be using "%p". See e.g. this printf (and family) reference.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

**ref is a pointer to a pointer to a struct test, *head is a pointer to a struct test.

The error is there, because whene referencing, **ref is of type struct test and you should use the dot . to get to a member of the struct:

  (**ref).data

head is a pointer to a struct test, and you can correctly use the -> operator there.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195