You can't define an array's size using a variable.
x
is a variable, so
a[x]
isn't allowed. You have to use
malloc
to allocate the array's memory. Your code shouldn't even compile!
I write C++, which allocates memory differently. But I believe this is what you want:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
printf("Enter the length of the character array:");
scanf("%d",x);
int* a = (int*) malloc(x * sizeof(int));
return 0;
}
malloc
allocates bytes, so you need to allocate enough of them to hold
x
int
s.
malloc
returns a pointer to the memory that it allocated. That's a
void*
, so you have to cast it to the type you want (an
int*
). You can then use
a
just like an array:
a[0]
...
a[x-1]
.