Thread: array of struct pointers

  1. #1
    jellyKing
    Guest

    array of struct pointers

    i have a function which creates an array of pointers to a struct like:

    Code:
    node *fn()
    {
           node *buf[MAX];
           <other code here>
           printf("buf:%d\n",buf[0]->num);
           printf("buf:%d\n",buf[0]->next->num);
           printf("buf:%d\n",buf[1]->num);
           printf("buf:%d\n",buf[1]->next->num);
           return *buf;
    }
    
    main()
    {
            node *control=fn();
            printf("%d\n",control->num);
            printf("%d\n",control->next->num);
            control++;
            printf("%d\n",control->num);
            printf("%d\n",control->next->num);
    }
    the problem is my printf's from main and from f() do not match..i do not understand why. The ones I see from f() are correct but the ones from main are not. why is this?

  2. #2
    Registered User
    Join Date
    Mar 2003
    Location
    UK
    Posts
    170
    The node pointer array in fn() is allocated from the local stack and will be lost when returned from fn(). You need to allocate memory for the pointer array. You need to return as a pointer array i.e ** If you're going to use as an array of node pointers. The 'control' memory needs to freed at some point when finished with.
    It would be best to pass the pointer array to fn() in the first place if its a fixed size and not return anything.
    Code:
    node **fn()
    {
           node **buf;  
           buf = (node **) malloc(sizeof(node **)*MAX);
    
           <other code here>
           printf("buf:%d\n",buf[0]->num);
           printf("buf:%d\n",buf[0]->next->num);
           printf("buf:%d\n",buf[1]->num);
           printf("buf:%d\n",buf[1]->next->num);
           return buf;
    }
    main()
    {
            node **top=fn();
            node **control=top;
    
            printf("%d\n",(*control)->num);
            printf("%d\n",(*control)->next->num);
            control++;
            printf("%d\n",(*control)->num);
            printf("%d\n",(*control)->next->num);
    
            free(top);
           
           return 0;
    }
    Last edited by Scarlet7; 04-12-2003 at 12:22 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MergeSort with array of pointers
    By lionheart in forum C Programming
    Replies: 18
    Last Post: 08-01-2008, 10:23 AM
  2. array of pointers to an array pointers
    By onebrother in forum C Programming
    Replies: 2
    Last Post: 07-28-2008, 11:45 AM
  3. Array of struct pointers - Losing my mind
    By drucillica in forum C Programming
    Replies: 5
    Last Post: 11-12-2005, 11:50 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM