Reputation: 619
I have some little error in C:
Error: expression must have a constant value
I know, that's mean that my limit must have a constant value, but how i can to solve that when i have this situation?
printf("Type limit: ");
scanf("%i",&limit);
int arr[limit];
Thanks.
EDIT:
Ok guys, another problem, sorry if i spam.
int num,limit,i;
printf("Type limit: ");
scanf("%i",&limit);
int *arr = (int*)malloc(limit*sizeof(int));
for(i=0;i<limit;i++)
{
printf("Type num %i: ",i);
arr[i] = scanf("%i",&num);
}
system("pause");
return 0;
error 4 error c2109 subscript requires array or pointer type
Upvotes: 0
Views: 4624
Reputation: 42083
Variable-length arrays with automatic storage duration are allowed since C99. In C89, it is not possible to allocate an array with automatic storage duration, size of which is not known at the compile time. Use malloc
to allocate it dynamically:
printf("Type limit: ");
scanf("%i", &limit);
int* arr = malloc(limit * sizeof(int));
and don't forget to call free(arr)
to deallocate this memory once you don't need it anymore.
To your question about initializing this array with values being read from stdin in a loop:
for(i = 0; i < limit; ++i)
arr[i] = scanf("%i", &num);
reads each value, stores it into num
variable and then 1
is assigned into arr[i]
since scanf
returns "number of input items successfully matched and assigned" (which is 1 in this case). You can read into array elements directly:
for(i = 0; i < limit; ++i)
scanf("%i", &arr[i]);
Upvotes: 4
Reputation: 3571
int *arr=malloc( limit*sizeof(int) );
This will allocated sufficient memory in the heap for your array of limit
int
’s.
But this array will be “dynamical” (the size is set at run-time), and it will be your responsibility to “free
” this memory when you not longer need it. Your variable arr will be just a pointer to that memory.
int arr1[10];
on the other hand separate a memory space for 10 int
in the stack, and your variable arr1
is that memory. The compiler need to know the size. If you past it to a function taking int*
it will “decay" to int*,
that is, a pointer to the first element arr1[0].
Upvotes: 0
Reputation: 33273
C89 and earlier versions of C didin't support run-time sizing of arrays. You need to turn on C99 (or newer) support in your compiler.
If you are using Linux you can either type:
gcc -std=c99
or
c99
to compile code written for c99.
Upvotes: 1
Reputation: 2239
You should use malloc
:
printf("Type limit: ");
scanf("%i",&limit);
int *arr = malloc(sizeof(int) * limit);
Upvotes: 5