c - Linked List Assistance -


i'm working on linked list in c insert , print functions. however, getting segmentation fault insert, , when try fix end 1 print function. appreciated.

    typedef struct node     {         struct node *next;         double value;     } nodet, *nodetp;      int listsize = 0;      int insert(nodet *firstele, int value)     {         nodetp temp;          if((temp = (nodetp)malloc(sizeof(nodet))) == null)         {             return 0;         }          // first node in list.         if(listsize == 0)         {             firstele->value = value;             firstele->next = null;         }         // finds end node , adds new node list.         else         {             while(temp != null)             {                 temp = temp->next;             }              temp->value = value;             temp->next = firstele;             firstele = temp;         }          listsize++;         return 1;     }      int print(nodet list)     {         printf("element: %.2f\n", list.value);         return 1;     }      int main(int argc, char* argv[])     {         // creates list.         nodetp list;          if((list = (nodetp)malloc(sizeof(nodet))) == null)         {             return 0;         }          list = null;          insert(list, 5);          print(list[0]);          insert(list, 15);          print(list[1]);          return exit_success;     }  

print issue

when comes print statements, using invalid syntax. created single pointer , allocated enough memory pointer , points to. did not create array of nodet elements. such, list[x] not work.

you need generate function locate 'x' element in list making. include in print function write. change take int of element want:

int print(nodet head, int element) {} 

don't forget check bounds in case element asked outside of current range.

all need step through elements desired one.

insert issue

in if/else statement, why trying iterate through 'temp'? 'temp' created in function , should have no other elements attached it. should iterating through 'firstele'. don't want set firstele = temp; on write there before , pointing else.

one way simplify code use head , tail. head never changes tail moves elements added. can have 'insert' return tail , when insert new element, provide tail , new element added there, no iteration needed.

memory issue

while not major program, adjust malloc new node till after have insured isn't first element. else, have block allocated never used. or, if first element added, free block.

and fred makes point. cause issues.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -