Reputation: 3
I want to make an array whose size is to be determined during run time i.e. user input.
I tried to do it like this:
printf("enter the size of array \n");
scanf("%d",&n);
int a[n];
But this resulted in an error.
How do I set the size of an array like this?
Upvotes: 0
Views: 855
Reputation: 318508
Unless you are using C99 (or newer) you need to allocate memory manually, e.g. using calloc()
.
int *a = calloc(n, sizeof(int)); // allocate memory for n ints
// here you can use a[i] for any 0 <= i < n
free(a); // release the memory
If you do have a C99-compliant compiler, e.g. GCC with --std=c99
, your code works fine:
> cat dynarray.c
#include <stdio.h>
int main() {
printf("enter the size of array \n");
int n, i;
scanf("%d",&n);
int a[n];
for(i = 0; i < n; i++) a[i] = 1337;
for(i = 0; i < n; i++) printf("%d ", a[i]);
}
> gcc --std=c99 -o dynarray dynarray.c
> ./dynarray
enter the size of array
2
1337 1337
Upvotes: 2
Reputation: 791869
You need to include the stdio.h
, declare n
and put your code in a function. Other than that what you've done should work.
#include <stdio.h>
int main(void)
{
int n;
printf("enter the size of array \n");
scanf("%d",&n);
int a[n];
}
Upvotes: 0