I'm trying to write a program, which reads a polynomial. I use C with Visual Studio 10(at work)/13(at home)
我正在尝试编写一个读取多项式的程序。我在Visual Studio 10中使用C(在工作中)/ 13(在家)
Code:
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.
}
gives
error C2075: 'poly' : array initialization needs curly braces
错误C2075:'poly':数组初始化需要花括号
If I try:
如果我尝试:
double poly[number];
I get:
error C2057: expected constant expression
错误C2057:预期的常量表达式
error C2466: cannot allocate an array of constant size 0
错误C2466:无法分配常量大小为0的数组
error C2133: 'poly' : unknown size
错误C2133:'poly':未知大小
This is the solution, special thanks to CoolGuy
这是解决方案,特别感谢CoolGuy
#include<stdlib.h>
void getPolynomial()
{
int number;
double *poly;
number = getInt(1, 10);
poly = malloc(number * sizeof(*poly));
// use array poly[]
free(poly);
}
1 个解决方案
#1
double poly[] = poly[number];
is not valid C. You have to use
是无效的C.你必须使用
double poly[number];
if your compiler supports C99. The above line creates a VLA(Variable Length Array) and this was introduced in C99. AFAIK, VS 2010 does not support C99, but VS 2013 does.
如果您的编译器支持C99。上面的行创建了一个VLA(可变长度数组),这是在C99中引入的。 AFAIK,VS 2010不支持C99,但VS 2013支持。
If that doesn't work you'll have to dynamically allocate memory using malloc
/calloc
:
如果这不起作用,您将不得不使用malloc / calloc动态分配内存:
double *poly;
poly = malloc(number * sizeof(*poly)); //sizeof(*poly)==sizeof(double)
//After poly's use,
free(poly);
#1
double poly[] = poly[number];
is not valid C. You have to use
是无效的C.你必须使用
double poly[number];
if your compiler supports C99. The above line creates a VLA(Variable Length Array) and this was introduced in C99. AFAIK, VS 2010 does not support C99, but VS 2013 does.
如果您的编译器支持C99。上面的行创建了一个VLA(可变长度数组),这是在C99中引入的。 AFAIK,VS 2010不支持C99,但VS 2013支持。
If that doesn't work you'll have to dynamically allocate memory using malloc
/calloc
:
如果这不起作用,您将不得不使用malloc / calloc动态分配内存:
double *poly;
poly = malloc(number * sizeof(*poly)); //sizeof(*poly)==sizeof(double)
//After poly's use,
free(poly);