简体   繁体   中英

Declaring arrays according the user input

i'm trying to declare arrays depending on the user input, consider if user enters 2, then i need to declare 2 arrays. like : int case1[10]={},case2[10]={} , i tried it using macros CONCAT but it didn't worked, so how can we do it?

You cannot do that. Variable declarations are a compile time thing, long before the user gets to interact with the program (at runtime). Macros are also expanded at compile time.

But whenever you have variables named foo1 , foo2 , foo3 , etc., why not just use an array instead? Then you can have foo[0] , foo[1] , foo[2] , and so on.

In your case standard "dynamic array" techniques apply. Either use a variable-length array:

int n = get_user_input_somehow();
int arr[n][10];

Or use traditional dynamic memory allocation:

int n = get_user_input_somehow();
int (*arr)[10] = malloc(n * sizeof *arr);
if (!arr) {
    handle error
}

And don't forget to release the memory when you're done:

free(arr);

In either case you can then use arr[i][j] to access elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM