Like Tree1Likes

Data Structures:

This is a discussion on Data Structures: within the C Programming forums, part of the General Programming Boards category; I made comments as to what I think is happening. I get the concept but still not grasping it totally. ...

  1. #1
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466

    Data Structures:

    I made comments as to what I think is happening. I get the concept but still not grasping it totally.

    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #define MAXCHARS 21
    
    struct music {
        char name[MAXCHARS];
        char artist[MAXCHARS];
        int number_of_songs;
        struct music *next;
    };
    
    void display(struct music *root)
    {
        struct music *temp=root;
        while(temp != NULL)
        {
            printf("%s ",temp -> name);
            temp = temp -> next;
        }
        printf("\n");
        
    }
    
    int main(int argc, const char * argv[])
    {
        int i = 0, j=0;
        struct music *root;
        root = NULL;                 /* initialize the top-of-stack pointer */
        
        char name[20];
        char artist[20];
        int number_of_songs = 0; 
        
        printf("Enter the following:\n");
        
        while (j < 3) {
            printf("\nName of the Band:");
            
            scanf("%s",&name[20]);
            printf("\nArtist:");
           
            scanf("%s",&artist[20]);
            printf("\nNumber of songs:\n ");
            
            scanf("%d",&number_of_songs);
            
        
            if (root == NULL) {                      // if == to end of line //
                root = malloc(sizeof(struct music)); // makes space //
                int size = strlen(name);             // finds length of name but makes a error //
                
                for (i=0;i<size;i++)
                    root->name[i] = name[i];  // loop is empty//
                root->next = NULL;
            }
            else                                // loop is not empty //
            {
                struct music *temp = root; {       // making a node //
                    struct music *prev = NULL; {  // until node is == to end of line //
                        
                        while (temp != NULL) {   // while the line is not ended //
                            prev = temp;         
                            temp = temp->next;
                        }
                        temp = malloc(sizeof(struct music));  // makes memory for temp //
                        temp -> name[i]=name[i];  // loop and pointer
                        temp -> next=NULL;        //points to the top //
                        prev -> next=temp;       // points to the new node //
    
                    };
                    j++;            // not working //
                };
            
                display(root);  
            }
             
        
            return 0;
        }
        
    }
    ]

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,659
    It is a linked list, not a stack.

    Your comments are everything that is wrong with making comments.

    Code:
                int size = strlen(name);             // finds length of name but makes a error //
    What error?
    Code:
                for (i=0;i<size;i++)
                    root->name[i] = name[i];  // loop is empty//
    The very line you commented makes the loop not empty.
    Code:
            else                                // loop is not empty //
    What loop?
    Code:
                        temp = malloc(sizeof(struct music));  // makes memory for temp //
    Obviously.
    Code:
                        temp -> name[i]=name[i];  // loop and pointer
    What does that mean?
    Code:
                        temp -> next=NULL;        //points to the top //
    A linked list is distinct from a stack.
    Code:
                        prev -> next=temp;       // points to the new node //
    Obviously.
    Code:
                    j++;            // not working //
    Why not?

    If you want to understand linked lists, there is a certain amount of code that everyone writes and that everyone considers a single operation, as if C had support for linked lists out of the box. This is because there is a certain amount of code that just inserts a node into a list, or a certain amount that deletes a node from a list, et cetera. These are all tasks that need to be understood in order to work with the data structure.

    The best tutorial I think is available is here. You don't have to read all of it, but come back when you have an understanding of the concept and a few of the basic operations, like how to insert a node in a list and delete a node in a list. Even with just that information you can start to use lists effectively.
    Last edited by whiteflags; 08-12-2013 at 10:37 AM.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,485
    > scanf("%s",&name[20]);
    You read a string, but it immediately overflows the end of the array.
    It's just scanf("%s",name);

    > int size = strlen(name); // finds length of name but makes a error //
    To copy a string, you need strlen(name)+1 bytes.

    But...
    > for (i=0;i<size;i++)
    > root->name[i] = name[i]; // loop is empty//
    You may as well just have
    strcpy(root->name,name);


    > struct music *temp = root; { // making a node //
    > struct music *prev = NULL; { // until node is == to end of line //
    Get rid of those braces at the end of these lines (and the corresponding closing braces as well).
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466
    I wrote the whole thing again. It's better but now working. Any more advice?

    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define MAXCHARS 21
    
    
    struct music {
        char name[MAXCHARS];
        char artist[MAXCHARS];
        int number_of_songs;
        struct music *next;
    };
    
    void input()
    {
        char name[MAXCHARS];
        char artist[MAXCHARS];
        int number_of_songs = 0;
        
        printf("Enter 3 Band Names, Artists and number of songs they have");
        gets(name);
        gets(artist);
        scanf("%d",&number_of_songs);
    
    }
    
    void output(char *name)
    {
        struct music *root;
        
        root=(struct music *)malloc(sizeof(struct music));
        if (root == (struct music *) NULL) {
            printf("Did not create enough memory");
            exit(1);
        }
        
        struct music *temp = root;
        struct music *prev = NULL;
        
        while (temp != NULL) {
            prev = temp;
            temp = temp->next;
        }
        temp = malloc(sizeof(struct music));
        strcpy(temp->name,name);
        temp -> next=NULL;
        prev -> next=temp;
        
    }
    void display(struct music *root)
    {
        struct music *temp=root;
        while(temp != NULL)
        {
            printf("%s ",temp -> name);
            temp = temp -> next;
        }
        printf("\n");
        
    }
    
    
    int main(int argc, const char * argv[])
    {
        
        input();
        
        output();
        
        display();
        
        
        
        return 0;
    }

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,485
    Yes, stop using gets().

    > void output(char *name)
    > void display(struct music *root)
    And where are these parameters in main when you call these functions?

    You didn't test this very well .
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466
    gets() is the only thing I can think of without having to use strlen( ) which keeps failing. I was using strlen during a for loop which I later found out I didn't have to use.

  7. #7
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466
    OK!! Please disregard my last comment. gets is the only thing I can think of to use without having to use a loop and strlen(). I have this example on my prior codes above.

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    2,701
    You should never use gets(). This is a very dangerous function that leads to many many problems. You should consider using fgets() instead.

    Jim

  9. #9
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466
    Fixed, thanks!

    Code:
     printf("Enter 3 Band Names, Artists and number of songs they have");
        fgets(name,MAXCHARS,stdin);
        fgets(artist,MAXCHARS,stdin);
        scanf("%d",&number_of_songs);

  10. #10
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    I suggest to read FAQ > Casting malloc - Cprogramming.com
    And also think about changing failure behavior - when utility function on failure exits the whole program - it maybe good for testing project, in real life situations is highly unexpected behavior.

    So better add return value to your functions that could fail and return 0 to indicate success and over value to indicate different failures that occurred.

    Calling function should examine the return value and decide the proper error handling behavior.
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  11. #11
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466
    Why is this failing in main.
    Code:
     temp=(structmusic*)(malloc(sizeof(structmusic));


    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct music {
        char *name;
        char *artist;
        int number_of_songs;
        struct music *next;
    };
    char* receiveInput(){
        char *s = (char*) malloc( 20 );
        scanf("%s",s);
        return s;
    }
    void get_inputs(struct music *ptr)
    {
        printf("%s","Enter the name:");
        ptr->name=receiveInput();
        printf("%s","Enter the artist:");
        ptr->artist=receiveInput();
        printf("%s","Enter the number of songs:");
        scanf("%d",&ptr->number_of_songs);
    }
    void add(struct music *root,struct music *ptr)
    {
        if (root==NULL)
        {
            root=(struct music*)malloc(sizeof(struct music));
            root->name=ptr->name;
            root->artist=ptr->artist;
            root->number_of_songs=ptr->number_of_songs;
            root->next=NULL;
        }
        else
        {
            struct music * temp=root;
            struct music * prev=NULL;
            while(temp)
            {
                prev=temp;
                temp=temp->next;
            }
            temp=(struct music*)malloc(sizeof(struct music));
            temp->name=ptr->name;
            temp->artist=ptr->artist;
            temp->number_of_songs=ptr->number_of_songs;
            temp->next=NULL;
            prev->next=temp;
        }
    }
    
    void output(struct music * root)
    {
        struct music *temp=root;
        while(temp)
        {
            printf("%s",temp->name);
            printf("\n");
            temp=temp->next;
        }
    }
    int main()
    {
        struct music * root=NULL;
        int i=0;
        while(i<3)
        {
            struct music * temp;
            temp=(struct music*)(malloc(sizeof(struct music));
                                 
                          get_inputs(temp);
                          add(root,temp);
                          output(root);
        }
                                 
        }

  12. #12
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    If by failing you mean failing to compile.... what does your compiler say? GCC said:

    Code:
    test.c:70:57: error: expected ‘)’ before ‘;’ token
    Think that's pretty clear. You have 4 open brackets and only 3 close brackets on that line. Compare it to the similar lines that compile correctly and fix it.


    You have a general problem with your add() call. I haven't read the whole thread so not sure if someones mentioned it already. You're passing a pointer to a struct. You can change the fields in that struct in the function, but you can't change the value of the pointer. That is, you calls to malloc to modify root and temp will set the value of the root and temp inside add(), but those changes will be lost as soon as the function returns, then they'll have the same values they did before the call.
    So nothing will actually get added!

    If you only change one pointer value, a common trick is to return the modified pointer. No good if you're modifying two values though. For this, you should pass a pointer to the pointer.

    Code:
    void add(struct music **root,struct music **ptr)
    {
        if (*root==NULL)
    ...
    ...
       add(&root, &temp);
    Hope that makes sense. Just remember that everything in C is passed by value. There's no way to modify an argument inside a function. You must always pass a pointer to the data to by modified. Arrays confuse the issue slightly but for this code, it's straightforward pointer-need.

  13. #13
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466
    Thank you. I keep making simple mistakes like this.

    Are you referring to passing by reference?

  14. #14
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    Indeed I am.

  15. #15
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    466
    I tried the way to mentioned but it didn't work. Now another issue is my while loop is never ending.

    Code:
     void display(struct music * root)
    {
        struct music *temp=root;
        while(temp)
        {
            printf("%s",temp->name);
            printf("\n");
            temp=temp->next;
        }
    }
    int main()
    {
        struct music * root=NULL;
        int i=0;
        
        while(i<3)
        {
            struct music * temp;
            temp=(struct music*)(malloc(sizeof(struct music)));
                                 
                          get_inputs(temp);
                          add(root,temp);
                          display(root);
        }
        i++;
        }

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-16-2005, 10:03 AM
  2. Data Structures
    By vex_helix in forum C Programming
    Replies: 2
    Last Post: 04-25-2004, 02:47 PM
  3. Data Structures
    By sonicsite in forum C Programming
    Replies: 3
    Last Post: 02-28-2002, 08:56 PM
  4. Data Structures
    By sonicsite in forum C Programming
    Replies: 2
    Last Post: 02-18-2002, 11:58 AM
  5. need help with data structures
    By straightedgekid in forum C++ Programming
    Replies: 0
    Last Post: 10-05-2001, 02:17 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21