Thread: c recursion in structures

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    31

    c recursion in structures

    hello guys, i read someone else's code which works. then i wrote this one myself to see if i can incorporate recursion in adding nodes to a linked list structure. in the debugger after the loop ought to end, it revives itself, assigns value 1 to num_m and starts all over again so irrespective of num_m, length() always return 2. this is beyond my comprehension. I've been on this for 3hrs and no luck

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    struct node{
        int a;
        struct node *next;
    };
    
    int add_node(struct node **head, int val, int num_m);
    int length(struct node *);
    
    int main(){
    
    struct node *head = NULL;
    struct node first;
    first.a = 5;
    first.next = NULL;
    head = &first;
    printf("%p", &first);
    add_node(&head, 5, 2);
    int count = length(head);
    
    printf("lenght is %d", count);
    
    }
    
    int add_node(struct node **head, int val, int num_m){
        int i;
        int x = 0;
        x = num_m;
        struct node *new_node;
        struct node *temp;
        while(x > 0){
            new_node = (struct node *)malloc(sizeof(struct node));
            new_node->a = val;
            new_node->next = NULL;
            (*head)->next = new_node;
            x--;
    
            if (x > 0){
                i = val+2;
                add_node(&new_node, i, x);
            }
    
        }
    }
    
    int length(struct node *head){
        if(head->next == NULL)
            return 1;
        else{
            return (1 + length(head->next));
        }
    }

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    If add_node is supposed to add num_m nodes to the list then you've made the mistake of using a loop and recursion at the same time. You want to just use the recursion. Your base case would be num_m <= 0 in which case you just return. The recursive call would pass in num_m - 1.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with Nested Structures and Arrays of Structures
    By Ignoramus in forum C Programming
    Replies: 4
    Last Post: 03-02-2010, 01:24 AM
  2. Accessing Structures Inside Structures
    By Mellowz in forum C Programming
    Replies: 1
    Last Post: 01-13-2008, 03:55 AM
  3. Structures, passing array of structures to function
    By saahmed in forum C Programming
    Replies: 10
    Last Post: 04-05-2006, 11:06 PM
  4. Help with structures and recursion
    By highsummonerbob in forum C Programming
    Replies: 2
    Last Post: 01-13-2004, 01:30 PM
  5. Replies: 5
    Last Post: 04-11-2002, 11:29 AM

Tags for this Thread