Declaring a table with unknown size (C)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Transmit
    New Member
    • Dec 2006
    • 11

    Declaring a table with unknown size (C)

    Hi everyone,

    I need to declare an array of chars but I don't know how big it will be from the start of the program.

    example:
    Someone gives me a name:
    John
    Array gets filled with john
    [j][o][h][n]

    so the size of this array is 4 chars (not more)!

    how can I declare an array that way?
    I tried: char tablename[] but that doesn't seem to work.

    Thanks in advance!!
  • willakawill
    Top Contributor
    • Oct 2006
    • 1646

    #2
    Originally posted by Transmit
    Hi everyone,

    I need to declare an array of chars but I don't know how big it will be from the start of the program.

    example:
    Someone gives me a name:
    John
    Array gets filled with john
    [j][o][h][n]

    so the size of this array is 4 chars (not more)!

    how can I declare an array that way?
    I tried: char tablename[] but that doesn't seem to work.

    Thanks in advance!!
    Hi. To size an array dynamically you need to use the 'new' and 'delete' keywords:
    Code:
    char *ar;
    //your code here
    ar = new char[sizeofstring + 1];
    //your code here
    delete [] ar;

    Comment

    • drhowarddrfine
      Recognized Expert Expert
      • Sep 2006
      • 7434

      #3
      "new" and "delete" are not valid in C. So you need to malloc to create space for the array but others more experienced than I can show you how.

      Comment

      • willakawill
        Top Contributor
        • Oct 2006
        • 1646

        #4
        Originally posted by drhowarddrfine
        "new" and "delete" are not valid in C. So you need to malloc to create space for the array but others more experienced than I can show you how.
        Oops. My mistake.

        Code:
        /* MALLOC.C: This program allocates memory with
         * malloc, then frees the memory with free.
         */
        
        #include <stdlib.h>         /* For _MAX_PATH definition */
        #include <stdio.h>
        #include <malloc.h>
        
        void main( void )
        {
           char *string;
        
           /* Allocate space for a path name */
           string = malloc( _MAX_PATH );
           if( string == NULL )
              printf( "Insufficient memory available\n" );
           else
           {
              printf( "Memory space allocated for path name\n" );
              free( string );
              printf( "Memory freed\n" );
           }
        }

        Comment

        Working...