# Question on array

• 11-25-2009
spurs01
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.

Code:

```#include<stdio.h> int n, decimal; int i, j, tmp; int number[100]; input_number() {  int ch;    printf("Enter how many element to store in array: ");         decimal = 0;             ch = getchar();     while(ch != '\n')     {         if('0' <= ch && ch <= '9')             {                     decimal = decimal * 10;                 decimal = decimal + (ch - '0');             }                     ch = getchar();     }         } input_array() {  int array;  for(i=0;i<decimal;i++)   {   printf("Enter array %d: ",i+1);           array = 0;             ch = getchar();     while(ch != '\n')     {         if('0' <= ch && ch <= '9')             {                     array = array * 10;                 array = array + (ch - '0');         }                     ch = getchar();     }   number[i]=array;   } }   main() {      input_number();  input_array();    n=decimal;  //print the unsorted numbers  printf("\nUnsorted number : ");  for(i=0;i<n;i++)   {   printf("%d, ",number[i]);   }     printf("\n");    for(i=0;i<n-1;i++)   {   for(j=0;j<n-i-1;j++)     {         if(number[j]>number[j+1])           {           tmp = number[j];           number[j] = number[j+1];           number[j+1] = tmp;           }         }   }    //print the sorted numbers  printf("Sorted number  : ");  for(i=0;i<n;i++)   {   printf("%d, ",number[i]);   } }```
• 11-25-2009
Epy
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;```
• 11-25-2009
Epy
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:

Code:

`array = calloc((size_t)arraylength, sizeof(int));`
malloc - C++ Reference
calloc - C++ Reference