Reputation: 318
I want the user to decide the size of my array
Can i do it?
I tried:
#define max 8
int a[max];
But then, user cant change a constant
I tried:
int i, a[i];
But it gives an error
Help?
Upvotes: 0
Views: 161
Reputation: 336
As mentioned in above malloc is best way as it won't depend on compiler. Also because realloc can be done when you find that u need to increase of decrease the size of array.
int size;
printf("What's the array size?\n");
scanf("%d", &size);
array = (int *)malloc(size * sizeof(*array));
.
.
.
.some stuff on array
array = (int *)realloc(array, 1024); // changing size of array according to user.
more details regarding realloc is here resizing buffer using realloc
Upvotes: 3
Reputation: 1498
For a clean solution, use malloc() function, instead of int array[size];
int size;
printf("What's the array size?\n");
scanf("%d", &size);
array=(int *) malloc(size*sizeof(int));
Upvotes: 2
Reputation: 6108
Assuming your compiler supports C99 and variable-length arrays, then the following code will work:
int size;
fputs("Array size? ", stdout);
scanf("%d", &size);
int array[size];
If your compiler does not, you'll have to use malloc
.
int size;
int* array;
fputs("Array size? ", stdout);
scanf("%d", &size);
array = malloc(size * sizeof(*array));
/* do stuff with array */
free(array); /* don't forget to free() when finished */
Some implementations support alloca
, which allocates on the stack like a variable-length array would, but this is non-standard.
Upvotes: 5
Reputation: 3067
You need to define the array after you ask the user for input.
int size;
printf("Please enter the size of the array");
scanf(" %d", &size);
int array[size];
Upvotes: 4