Jkrowling
Jkrowling

Reputation: 13

Pointer to function (list)

I have to write this program but I can't do any changes in function main, this program works when Node* head is declared as a global Variable (functions does not contain "Node* head" in parameters). this program compiles successfully, but then is segmentation fault (I know why, Head was not changed and it's still 0, but I don't know how to fix that). Any ideas ?

#include <iostream>
#include <cstdlib>
using namespace std;
struct Node{
  int val;
  Node* next;
};
void addBeg(Node* head,int val)
{
  Node* temp = (Node*)malloc(sizeof(Node));
  temp->val=val;
  temp->next=head;
  head=temp;
}
int main()
{
  Node* head=0;
  addBeg(head,1);
  cout << head->val << endl; //checking if head was changed correctly 
  return 0;
}

Upvotes: 1

Views: 48

Answers (2)

VolAnd
VolAnd

Reputation: 6407

If you want to change pointer inside function send "pointer to pointer", e.g.:

#include <iostream>
#include <cstdlib>
using namespace std;
struct Node{
  int val;
  Node* next;
};
void addBeg(Node** head,int val)    // Node** instead of Node*
{
  Node* temp = (Node*)malloc(sizeof(Node));
  temp->val=val;
  temp->next=*head;
  *head=temp;                  // *head  instead of head
}
int main()
{
  Node* head=0;
  addBeg(&head,1);   // &head instead of head
  cout << head->val << endl; //checking if head was changed correctly 
  return 0;
}

EDIT:

Or just use reference parameter for pointer:

void addBeg(Node* &head,int val)
{
  Node* temp = (Node*)malloc(sizeof(Node));
  temp->val=val;
  temp->next=head;
  head=temp;
}

Upvotes: 2

WhozCraig
WhozCraig

Reputation: 66204

You need to pass the head pointer by reference if you're going to modify it. Anything else will require modification of main(), which is apparently off-limits:

Change this:

void addBeg(Node* head, int val)

To this:

void addBeg(Node*& head, int val) // NOTE: see reference &

See it live here

That said, you should be using new, not malloc, and ideally using a standard container like std::vector<>, std::list<>, std::deque<> rather than this, but that is unrelated to the question.

Upvotes: 0

Related Questions