By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,445 Members | 1,329 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,445 IT Pros & Developers. It's quick & easy.

Declaring a table with unknown size (C)

P: 11
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!!
Dec 27 '06 #1
Share this Question
Share on Google+
3 Replies


100+
P: 1,646
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:
Expand|Select|Wrap|Line Numbers
  1. char *ar;
  2. //your code here
  3. ar = new char[sizeofstring + 1];
  4. //your code here
  5. delete [] ar;
Dec 27 '06 #2

drhowarddrfine
Expert 5K+
P: 7,435
"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.
Dec 27 '06 #3

100+
P: 1,646
"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.

Expand|Select|Wrap|Line Numbers
  1. /* MALLOC.C: This program allocates memory with
  2.  * malloc, then frees the memory with free.
  3.  */
  4.  
  5. #include <stdlib.h>         /* For _MAX_PATH definition */
  6. #include <stdio.h>
  7. #include <malloc.h>
  8.  
  9. void main( void )
  10. {
  11.    char *string;
  12.  
  13.    /* Allocate space for a path name */
  14.    string = malloc( _MAX_PATH );
  15.    if( string == NULL )
  16.       printf( "Insufficient memory available\n" );
  17.    else
  18.    {
  19.       printf( "Memory space allocated for path name\n" );
  20.       free( string );
  21.       printf( "Memory freed\n" );
  22.    }
  23. }
Dec 27 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.