2

This might be a question with a very simple solution but I can't get my head around it... I'm trying to implement linked list for a school proyect using structures but when I initialize the very first node, malloc seems to make no effect at all

here's my code so far:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

typedef struct Node Node;
struct Node
{
    int data;
    Node *next;
};

void init_List(Node *head, int data)
{
    head = (Node*)malloc(sizeof(Node));
    if(head == NULL)
    {
        printf("Memory Allocation Error");
        return;
    }
    head->data = data;
    head->next = NULL;
}

int main()
{
    Node *head = NULL;
    int N;
    printf("N: ");
    scanf("%d", &N);
    init_List(head, N);
    printf("%d", head->data);
}

whatever number I read to make the first data of my node prints as cero. don't know what could be happening. thanks for the help!

kfsone
  • 23,617
  • 2
  • 42
  • 74
Jesus Omar
  • 21
  • 1
  • 4

2 Answers2

2

When you passed head to the function init_List, a local copy of head is made and then memory is allocated to this local pointer. In main, head still points to NULL.

You need to use pointer to pointer in function parameter.

void init_List(Node **head, int data)
{
    *head = malloc(sizeof(Node));
    if(*head == NULL)
    {
        printf("Memory Allocation Error");
        return;
    }
    (*head)->data = data;
    (*head)->next = NULL;
}

Your function call should be like

init_List(&head, N);  

Also note that, do not cast return value of malloc.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

In fact you already initialized the list in statement

Node *head = NULL;

So what you need is a function that will push front integers in the list. The function can look the following way

void push_front( Node **head, int data )
{
    Node *tmp = malloc( sizeof( Node ) );

    if ( tmp != NULL )
    {
        tmp->data = data;
        tmp->next = *head;
        *head = tmp;
    }
    else
    {
        printf( "Memory Allocation Error" );
    }
}

And the function is called the following way

push_front( &head, n );

Take into account that it is a bad idea to name variables with one capital letter.

As for your problem then function parameters are their local variables. So any changing of a local variable does not influense on the original argument. Functions deal with copies of their arguments.

So in the function

void init_List(Node *head, int data)
{
    head = (Node*)malloc(sizeof(Node));
    //...

there is changed local variable head. Though it has the same name as the argument that is used to call the function nevertheless any changes of the local variable do not influense on the argument. The original argument will not be changed. You have to declare the parameter as a pointer to pointer Node **head.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335