Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C allocating array of pointers

  1. Apr 25, 2013 #1
    I need some help with this piece of code I wrote earlier, it is compiling correctly but when I try to use my tester program it crashes.


    I am trying to create an array of pointers to struct Nodes
    Code (Text):

    typedef struct Node *NodeP;

    struct Node
    {
        NodeP next;
        EmployeeP info;
    };


    struct EmployeeList
    {
        NodeP* root;
        int size;
    };


    EmployeeListP newEmployeeList(int size)
    {
        //Creating employeelist and allocating memory for the array or pointers to nodes
        EmployeeListP e=malloc(sizeof(struct EmployeeList));
        e->root=malloc(sizeof(NodeP)* (size*2));
        int i;
        if(e==NULL || e->root==NULL)
        {
            fprintf(stderr,"Failed to allocate memory!\n");
            exit(1);
        }
        //Initializing list size and all pointers to NULL
        e->size=size;
        for(i=0;i<size*2;i++)
        {
            e->root[i]->info=NULL;
            e->root[i]->next=NULL;
        }

        return e;

    }

     

    test program where it crashes
    Code (Text):

    #include <stdio.h>
    #include <stdlib.h>
    #include"Employee.h"
    #include"EmployeeList.h"

    int main(void)
    {
        EmployeeListP e= newEmployeeList(10);

        return 0;
    }
     
     
  2. jcsd
  3. Apr 25, 2013 #2

    Mark44

    Staff: Mentor

    This line in your newEmployeeList function looks suspect to me.
    Code (Text):
    e->root=malloc(sizeof(NodeP)* (size*2));
     
    What's the purpose of 2 in the line above?
    Also, I think you should cast the value returned by malloc as NodeP.
     
  4. Apr 25, 2013 #3
    I have to make the array twice the size of the parameter passed in by the user. I am creating a hash table program and that is one of the specifications.
     
  5. Apr 25, 2013 #4

    rcgldr

    User Avatar
    Homework Helper

    During initialization, you haven't allocated any nodes for e->root to use, only the pointers, so all you can do at this point is:

    Code (Text):

        for(i=0;i<size*2;i++)
        {
            e->root[i] = NULL;
        }
     
    or you could allocate nodes:

    Code (Text):

        for(i = 0; i < size*2; i++)
        {
            e->root[i] = (NodeP) malloc(sizeof(Node));
            e->root[i]->info = NULL;
            e->root[i]->next = NULL;
        }
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C allocating array of pointers
  1. Arrays and pointers in C (Replies: 10)

Loading...