Search code examples
clinked-listinsertion

Inserting an Element to a Linked List


I am working for a C exam and while trying to insert an element to a linked list, I am encountering with a runtime problem. My only purpose is adding 4 elements to list and then printing the list. However, it gives an error. I already looked some insertion codes and my code seems right. Can't see the error. Any assistance would be appreciated.

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

struct ders{
    char kod;
    struct ders *next;

}*header;
typedef struct ders Ders;
void add(Ders*,Ders*);
void print(Ders*);

int main(void)
{

header = NULL;
Ders *node = NULL;
int i = 0;
char c;
while(i<4)
{
    scanf("%c",&c);
    node = (Ders*)malloc(sizeof(Ders));
    node->kod = c;
    node->next = NULL;
    add(header,node );
    i++;


}
print(header);

return 0;
}

void add(Ders *header, Ders *node)
{
    if(header == NULL){
        header = node;
        header->next = NULL; }
    else{
        node->next = header;
        header = node;

    }
}

void print(Ders *header)
{
Ders *gecici = header;

while(gecici != NULL){
    printf("%c\n",gecici->kod);
    gecici = gecici->next;
}
}

Solution

  • As nihirus stated, "The pointer is passed by value. Thus you can change the memory it points but you can't change the actual pointer, i.e. make it point to something else."

    Your modification resulted in error *header is not member of struct because -> has a higher precedence than *

    Try using (*header)->next = NULL instead.

    C operator precedence: http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm