我正在尝试编写一个读取多项式的程序。 我将 C 与 Visual Studio 10(工作时)/13(在家)一起使用
代码:
void getPolynomial()
{
int number;//Quantity of the polynomial
number = getInt(1, 10);
//getInt(min, max) Read a number from the user
//and return an int value between min and max
double poly[] = poly[number];
//I try to fix this line.
//It should create an array with as many fields,
//as the user wants to have.
}
给出
error C2075: 'poly' : array initialization needs curly braces
如果我尝试:
double poly[number];
我得到:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'poly' : unknown size
这就是解决方案,特别感谢 CoolGuy
#include<stdlib.h>
void getPolynomial()
{
int number;
double *poly;
number = getInt(1, 10);
poly = malloc(number * sizeof(*poly));
// use array poly[]
free(poly);
}
最佳答案
double poly[] = poly[number];
无效 C. 您必须使用
double poly[number];
如果您的编译器支持 C99。上面的行创建了一个 VLA(可变长度数组),这是在 C99 中引入的。 AFAIK,VS 2010 不支持 C99,但 VS 2013 支持。
如果这不起作用,您必须使用 malloc
/calloc
动态分配内存:
double *poly;
poly = malloc(number * sizeof(*poly)); //sizeof(*poly)==sizeof(double)
//After poly's use,
free(poly);
关于c - 如何编写一个用户可以输入的可变大小的数组[变量]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30139339/