Thread: Problem returning struct pointer

  1. #1
    Registered User
    Join Date
    Nov 2010

    Problem returning struct pointer


    I'm having trouble defining a method that is supposed to return a pointer to a struct:

      count_table_t* table_allocate(int size)
              count_table_t *test;
              return test;
    where count_table_t and list_node_t are defined in the header file as:

    typedef struct list_node list_node_t;
    struct list_node {
      char *key;
      int value;
      list_node_t *next;
    typedef struct count_table count_table_t;
    struct count_table {
      int size;
      //an array of list_node pointers
      list_node_t **list_array;
    I get a seg fault when running the method. Ideas? Essentially what I'm trying to do is make a count_table object with size: (size*list_node), and then return it.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > count_table_t *test;
    > test=malloc(sizeof(list_node_t)*size);
    Try using the same type.

    In fact, DON'T use a type at all in the malloc call.
    test = malloc ( sizeof(*test) * size );
    You can change the type of test, and the malloc will always be right.
    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.

  3. #3
    Registered User
    Join Date
    Nov 2010

    Does that method do what it is intended to do? Create a count_table_t pointer object and return it?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I'm donating my vector lib.
    By User Name: in forum C Programming
    Replies: 23
    Last Post: 06-24-2010, 06:10 PM
  2. help assignment due tomorrow
    By wildiv in forum C Programming
    Replies: 6
    Last Post: 01-27-2010, 08:38 PM
  3. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. struct pointer problem (out of scope?)
    By Axpen in forum C Programming
    Replies: 4
    Last Post: 05-17-2005, 09:48 AM