开发者

Problem with a linked list

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 <stdl开发者_高级运维ib.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;
 }


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)


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


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


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


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, ...)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜