Question on array

This is a discussion on Question on array within the C Programming forums, part of the General Programming Boards category; Hi ,
I have question about array. The program below has a fix array(100). I want the size of
the ...

Question on array

Hi ,

I have question about array. The program below has a fix array(100). I want the size of
the array to be determined by the user. How to write the code ?

The function "input_number" ask user to enter the size of the array. And i would like to allocate the entered value to be the size of the array. This way, user can enter more than 100 and my program will not crash.

If you're going to use C99, you can just use variable length arrays which are very straightforward:

Code:

int arraylength = 502;
int array[arraylength];

Otherwise, let me introduce malloc():

Code:

int arraylength = 502;
int *array;
/* allocate memory for arraylength number of integers
size_t is the appropriate type for malloc and the type of sizeof()
you do not need to cast malloc as an int type, this is unnecessary in ISO C
see http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1047673478&id=1043284351
*/
array = malloc((size_t)arraylength * sizeof(int));
if (!array)
{
printf("\nMalloc failed!");
exit(EXIT_FAILURE);
}
/* do stuff */
/* free up the memory that was allocated, set the array pointer to NULL so nothing else can use that now freed up memory block */
free(array);
array = NULL;

Last edited by Epy; 11-25-2009 at 10:02 AM.
Reason: added some more notes

Should've mentioned that this is part of the C standard library. Also, you can check out calloc() which does the same thing except it initializes that memory block to 0s. Its syntax is slightly different: