Problem with malloc and struct

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stdq
    New Member
    • Apr 2013
    • 94

    Problem with malloc and struct

    Hello, everyone. I'm trying to implement a stack using the following struct:

    Code:
    typedef struct stackOfStrings {
        char **arrayOfStrings;
    } StackOfStrings;
    Then, arrayOfStrings will contain strings. My idea is to use the following function to initialize it with as an empty array of strings, and then use realloc everytime a new element is to be added to the stack:

    Code:
    void initializeStackOfStrings( StackOfStrings *s )
    {
        s->arrayOfStrings = ( char ** )malloc( 1 * sizeof( char * ) );
        
        *( s->arrayOfStrings ) = ( char * )malloc( 0 * sizeof( char ) );
        
        printf( "%d\n", sizeof( s->arrayOfStrings ) );
    }
    This last statement is just there to help me check if the stack is indeed empty. However, it prints 4, instead of 0. What am I doing wrong in this function? Thanks in advance!
  • stdq
    New Member
    • Apr 2013
    • 94

    #2
    I apologize, I think the answer 4 was to be expected, after all I created an empty array of strings, but an existing array nevertheless, right?

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Er..

      Code:
      *( s->arrayOfStrings ) = ( char * )malloc( 0 * sizeof( char ) );
      Shouldn't your empty string be 1 char containing \0?

      Or did you mean to just set the array elements to zero to mean "no string"?

      Either way will work but you need to pick one method.

      Here you are allocating zero bytes. ??


      Note you have an array as a stack. The stack is empty when all the pointers in the array are zero. Or all the pointers point to null strings.

      Have you considered overflow? You can't easily add elements to an array.

      Can you have empty strings in the middle of the stack?

      How do you know the number of elements in the stack or do you just use the number of elements in the array?

      Please post again.

      Comment

      Working...