1

I am learning about linked lists, and I want to know if it is okay to pass by address operator or by pointer in the parameter for the given function:

void Push(struct Node **head_ref, int data)
{
    struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}

void Push(struct Node *&head_ref, int data)
{
    struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = data;
    new_node->next = head_ref;
    head_ref = new_node;
}
trincot
  • 317,000
  • 35
  • 244
  • 286

2 Answers2

2

struct Node *&head_ref is not valid C. It's how you would declare a reference parameter(a reference to pointer in this case) in C++.

So only the first version is valid in C.

When you call the function, you use the address operator with your variable.

struct Node *head = NULL;
Push(&head, 1);
Push(&head, 2);
thirdeye
  • 150
  • 7
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

In C, it is only passed by value. Ex in C:

int a;
int *p = &a;
foo(&p); //address of pointer(also a value) is passed to access "int a"

In C++, it is actual pass by reference: Ex in c++:

#include <iostream>
void foo(int& x){
    x = 0; //changes a value to 0
}

int main()
{
    int a = 5;
    foo(a);
    std::cout<<a<<std::endl; //prints 0
    return 0;
}

also please have a look at What exactly is the difference between "pass by reference" in C and in C++?

thirdeye
  • 150
  • 7