As others already noted, you need to create the array
after you know its size. With a
C99
compliant compiler (like
GCC
) you may write:
Please note: in order to simplify the code, I have omitted checking the
scanf
return value. You should always perform such a check in the actual code.
#include <stdio.h>
int main()
{
int x;
int i;
printf("Enter the value of 'x'\n");
scanf("%d", &x);
int arr[x];
printf("Enter %d elements\n",x);
for(i=0;i<x;i++)
{
scanf("%d", &arr[i]);
}
printf("the digits you entered are as follows: \n");
for(i=0;i<x;i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
return 0;
}
On the other hand, with a not-
C99
-compliant compiler you have to write something like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
int i;
printf("Enter the value of 'x'\n");
scanf("%d", &x);
int * arr = (int *) malloc( sizeof(int) * x); if ( ! arr ) return -1;
printf("Enter %d elements\n",x);
for(i=0;i<x;i++)
{
scanf("%d", &arr[i]);
}
printf("the digits you entered are as follows: \n");
for(i=0;i<x;i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
free (arr);
return 0;
}