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]);
}
}