我可以在定义数组后通过数组 brackets/parameters 内的用户输入来定义变量吗?
Can I define a variable through user input inside the brackets/parameters of an array AFTER defining the array?
例如,我可以这样做吗:
int i, number_of_values, variable[i];
printf("Enter the number of values you would like to insert: \n");
scanf("%d", &number_of_arrays);
for (i=0; i<number_of_values; i++)
而不是使用这样的方法:
printf("Enter the number of values you would like to insert: \n");
scanf("%d", &number_of_values);
int variable[no_of_values];
可以吗?
谢谢!
Is it possible?
否,因为变量i
未初始化。在 C 语言中,使用未初始化的自动变量调用未定义的行为。
数组只是指定大小的一块连续内存。要分配一个数组,您必须指定它的大小。
但是,在某些情况下,您可能事先不知道所需的大小。对于这些情况,我们有动态内存 malloc。
您可以使用 malloc 在 运行 时分配所需的内存。
int* a;
a=(int *)malloc(sizeof(int)*required_size);
然后像访问数组一样轻松地访问此内存,例如a[i]
或者通过取消引用例如*(a + i)
这一行会给你一个错误:
int i, number_of_values, variable[i];
编译器不知道为数组 variable[i]
保留多少内存,因为他不知道 i
的值。
唯一的机会是动态内存分配。
例如,我可以这样做吗:
int i, number_of_values, variable[i];
printf("Enter the number of values you would like to insert: \n");
scanf("%d", &number_of_arrays);
for (i=0; i<number_of_values; i++)
而不是使用这样的方法:
printf("Enter the number of values you would like to insert: \n");
scanf("%d", &number_of_values);
int variable[no_of_values];
可以吗?
谢谢!
Is it possible?
否,因为变量i
未初始化。在 C 语言中,使用未初始化的自动变量调用未定义的行为。
数组只是指定大小的一块连续内存。要分配一个数组,您必须指定它的大小。 但是,在某些情况下,您可能事先不知道所需的大小。对于这些情况,我们有动态内存 malloc。 您可以使用 malloc 在 运行 时分配所需的内存。
int* a;
a=(int *)malloc(sizeof(int)*required_size);
然后像访问数组一样轻松地访问此内存,例如a[i]
或者通过取消引用例如*(a + i)
这一行会给你一个错误:
int i, number_of_values, variable[i];
编译器不知道为数组 variable[i]
保留多少内存,因为他不知道 i
的值。
唯一的机会是动态内存分配。