Thread: How to search in a stack and a linked list?

  1. #1
    Registered User
    Join Date
    Dec 2015
    Posts
    1

    How to search in a stack and a linked list?

    I need to search elements of a stack and a linked list. I implemented stack using linked list I have search both function to do it.

    Code:
    struct student{
        char name[100];
        char surname[100];
        char roll[10];
        char department[50];
        struct student *next;
    };
     
    struct theStack{
        struct student *head;
        struct student *pop;
        struct student st;
    };
     
    struct theStack myStack;
     
    void search_both(){
         struct student *a;
         struct theStack *x;
    
         a=(struct student*)malloc(sizeof *a);
         x=(struct theStack*)malloc(sizeof *x);
    
            while(strcmp(a->name, x->st.name)==0){
                while(strcmp (a->surname, x->st.surname)==0){
                    printf("%s %s and %s %s taking both classes",a->name, a->surname,x->st.name,x->st.surname);
                    a=a->next;
                    x=x->st.next;
                
            }
         }
         free(a);
         free(x);
    }

    what must be the wrong part of my code?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Surely a and x should be parameters to search_both()?

    Calling malloc just creates blocks of memory filled with junk data which you then try and process.

    Then you try and free() something else having traversed your data structures.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stack Linked List query
    By Josh Heathcote in forum C Programming
    Replies: 1
    Last Post: 03-10-2014, 11:31 PM
  2. STACK/FIFO as a linked list
    By BlackOps in forum C Programming
    Replies: 2
    Last Post: 07-24-2009, 02:04 PM
  3. Stack in linked list
    By mag_chan in forum C Programming
    Replies: 2
    Last Post: 11-09-2005, 05:31 AM
  4. Linked list Stack question
    By lyrick in forum C++ Programming
    Replies: 4
    Last Post: 09-23-2005, 06:23 AM
  5. linked list stack question
    By Drew in forum C++ Programming
    Replies: 2
    Last Post: 09-11-2003, 05:05 AM

Tags for this Thread