Hi all,

I am a beginner in c, and i am receiving an error in my code, I am writing the code to reverse the elements of a linked list, the code is as follows:

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

typedef struct node
{
        int data;
        struct node *next;
}element;

int insertElements(element **head, int d)
{
        element *ele;
        ele = (element*)malloc(sizeof(element));
        ele->data = d;
        ele->next = *head;

        *head = ele;
        return 1;
}

int reverseLinkedList1(element **head)
{
        element *temp;
        element *t2 = NULL; // some warning here cant figure out what is the incompatibility here.
        element *t3;

        *temp = *head;

        while(temp)
        {
                t3 = temp->next;
                temp->next = t2;
                t2 = temp;
                temp = t3;
        }
        return 1;
}

int main()
{
        element *ele;
        
        ele = (element *)malloc(sizeof(element *));
        ele->data = 12;
        ele->next = NULL;
        
        insertElements(&ele, 15);
        insertElements(&ele, 43);
        
        element *ele2 = (element*)malloc(sizeof(element *));
        ele2 = ele;
        printf("Before reversing\n");
        while(ele)
        {
                printf("%d ",ele->data);
                ele = ele->next;
        }
        reverseLinkedList1(&ele2);
        printf("\nAfter reversing\n");
        while(ele2)
        {
                printf("%d ",ele2->data);
                ele2 = ele2->next;
        }
        printf("\n");
        return 0;
}

Any clarification regarding pointers would be highly appreciated.
:sweat:

Recommended Answers

All 4 Replies

lines 13, 43 and 50: C language does not require you to typecast the return value of malloc(), but c++ does.

line 27: Attempting to dereference a pointer that has never been initialized. Remove the star in front of temp should fix that. temp = *head;

But now i am getting the same warning in the line 31:

warning: assignment from incompatible pointer type

The change shown below made it compile cleanly with vc++ 2008 express compiler

int main()
{
        element *ele, *ele2; // << CHANGED THIS LINE
        
        ele = (element *)malloc(sizeof(element *));
        ele->data = 12;
        ele->next = NULL;
        
        insertElements(&ele, 15);
        insertElements(&ele, 43);
        
        ele2 = (element*)malloc(sizeof(element *)); // << CHANGED THIS LINE

yes, i got the code working , thanks for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.