Problem returning struct pointer

This is a discussion on Problem returning struct pointer within the C Programming forums, part of the General Programming Boards category; Hi-- I'm having trouble defining a method that is supposed to return a pointer to a struct: Code: count_table_t* table_allocate(int ...

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    22

    Problem returning struct pointer

    Hi--

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

    Code:
      count_table_t* table_allocate(int size)
      {
              count_table_t *test;
              test=malloc(sizeof(list_node_t)*size);
              return test;
      }
    where count_table_t and list_node_t are defined in the header file as:

    Code:
    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,671
    > 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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    22
    Ok.

    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, 07: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

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