c - array to create a linked-list -


typedef struct num{     int num;     int pre;     struct num* next; }num;  num list[10]= {{3,4},{2,1},{6,5},{7,2},{4,3},{3,9},{5,6},{1,3},{8,4},{10,0} };  #include <stdio.h>  int main(){      int cnt;     num *ptr = null;      num temptwo;     (cnt = 0; cnt < 10; cnt++) {         temptwo = list[cnt];          ptr->next = &temptwo; //error         ptr = ptr->next;     }      (cnt = 0; cnt<10; cnt++) {         printf("num: %d, pre: %d\n",ptr->num,ptr->pre);         ptr = ptr->next;     } } 

i want make linked-list array 'list' using pointer ptr.

error: bad access 

what can solve problem?

this should trick

#include <stdio.h>  typedef struct num{     int num;     int pre;     struct num* next; }num;  num list[10]= {     {3,4},{2,1},{6,5},{7,2},{4,3},{3,9},{5,6},{1,3},{8,4},{10,0} };  int main(){      int cnt;     num *head, *ptr;      list[9].next = null;               // marks end of list     (cnt=8; cnt>=0; cnt--)         list[cnt].next = &list[cnt+1]; // point next list item     head = &list[0];                   // point first list item      // test     ptr = head;     while (ptr) {         printf ("%d %d\n", ptr->num, ptr->pre);         ptr = ptr->next;     }    return 0; } 

program output:

3 4 2 1 6 5 7 2 4 3 3 9 5 6 1 3 8 4 10 0 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -