1

I have a problem with this small program. It added some value to list. If I uncomment //printf("%d",first->val); the program gives error. Everything seems to be ok ;(

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

 typedef struct element {
   struct element *next;
   int val;
 } el_listy;

el_listy *first = 0;


void add_to_list(el_listy *lista, int value)
{

 if(lista == 0)
    {
        lista = malloc (sizeof(el_listy));
        lista->val = value;
        lista->next = 0;
        printf("added as first \n");
    }
        else
        { printf("added as fsecond  \n");
    el_listy *wsk = lista,*tmp;

                while(wsk->next != 0) wsk = wsk->next;

                tmp = malloc (sizeof(el_listy));
                tmp->val = value;
                tmp->next = 0;  

                wsk->next = tmp;                    
        }
}

 int main ()
 {
         add_to_list(first,2);
            add_to_list(first,4);
            //printf("%d",*first->val);
            system("pause");
   return 0;
 }

5 Answers 5

4

first->val is just like (*first).val, you can't use them both. also, as missingno said, add_to_list never changes first you should pass it's address as argument, not the pointer itself, meaningadd_to_list(&first,4); (and change the implementation of add_to_list as well)

Sign up to request clarification or add additional context in comments.

Comments

2

Your program never changes the value of first. It remains a null pointer and thus gives an error when dereferenced.

Comments

1

-> already follows a pointer, so the * tries to treat first as pointer to pointer to el_listy. You might find cdecl helpful.

Comments

1

You should use either (*first).val or first->val. Otherwise you get the wrong level of indirection.

Comments

0

Yes, it's a simple mistake.

fitsr won't change after *add_to_list()* function is called.

You should define function like this:

add_to_list(El_list **lista, ...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.