Search code examples
carraysscanfvariable-length-array

Scanf array limit in C?


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


Solution

  • You should use malloc:

    printf("Type limit: ");
    scanf("%i",&limit);
    int *arr = malloc(sizeof(int) * limit);