0

I want to write a program where the user is prompted to enter a integer, and I want my list's size to be exactly that integer. Here is my attempt:

int main(void){

    int target;
    printf("Enter # of elements in list: ");
    printf("\n");
    scanf("%d", &target);


    // Initialize List
    int list[target];
    // Code to populate list from 1 to target here

    return 0;
}

I'm getting a error that says the size arguement has to be a constant value, is there a way around this or am i forced to define a max size?

user2917692
  • 147
  • 1
  • 3
  • 10

2 Answers2

2

You can do this in C99 (or later), but your compiler may be set to C89/C90/ANSI-C by default. Try passing -std=c99 on the command-line.

If your compiler doesn't support C99-mode you'll need to use dynamic allocation via malloc:

int * list = malloc(target * sizeof *list);

You should check if list isn't NULL, in case the malloc failed and don't forget to call free(list) when you're done with it!

Be aware that you've defined list as an int, and you're reading it with scanf("%d") so it can be a negative value. That can lead to some undesirable behaviour. So consider changing the declaration to size_t (the type that malloc and VLA's expect). Then read it with %zu (or %u if %zu isn't available) instead of %d.

Finally, you should check the return-value of scanf to make sure your value was read correctly, if it's less than the number of values you want to read (1 in your case) it will mean that value was not read and the contents of your target remain unchanged. In your case target will have undefined contents and so your program would invoke undefined behaviour if the user doesn't enter a valid number.

Community
  • 1
  • 1
Kninnug
  • 7,992
  • 1
  • 30
  • 42
1

That is called variable-length array whose size is determined during run time instead of at compile time in case of automatic arrays. Variable-length arrays is supported by C99 and C11, however it's a conditional feature and the implementations aren't required to support it. gcc supports it and you should compile with the flag -std=c99. Another option is to dynamically allocate your array.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int target;
    printf("Enter # of elements in list: ");
    scanf("%d", &target);

    int *list = malloc(d * sizeof *list);
    if(list == NULL) {
        printf("Not enough memory to allocate.\n");
        return 1;
    }

    // do stuff with list

    // after you are done with list

    free(list);
    list = NULL;

    return 0;
}
ajay
  • 9,402
  • 8
  • 44
  • 71