简体   繁体   English

根据用户输入声明数组

[英]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. 我试图根据用户输入声明数组,考虑如果用户输入2,那么我需要声明2个数组。 like : int case1[10]={},case2[10]={} , i tried it using macros CONCAT but it didn't worked, so how can we do it? 像: int case1[10]={},case2[10]={} ,我使用宏CONCAT进行了尝试,但没有成功,那么我们该怎么做呢?

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? 但是,每当您拥有名为foo1foo2foo3等的变量时,为什么不只使用数组呢? Then you can have foo[0] , foo[1] , foo[2] , and so on. 然后,您可以拥有foo[0]foo[1]foo[2]等。

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. 无论哪种情况,都可以使用arr[i][j]访问元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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