c - 如何编写一个用户可以输入的可变大小的数组[变量]?

标签 c arrays

我正在尝试编写一个读取多项式的程序。 我将 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/

相关文章:

XP 新手上的 CodeBlocks MinGW。是否可以在每次编译时覆盖同一个exe?里面有进一步的解释

python - 成对组合来自两个数组的元素

php - 如何通过连接从 MySQL select 获取嵌套数组

java - 为什么 jvm 在我回拨 java 函数时崩溃?

c++ - 错误,* 的运算符必须是指针

c++ - Trie删除不成功

c - 用C格式化pendrive

javascript - 根据javascript中的顺序号将对象推送到数组

java - 将大文本文件加载到 int 数组中的最快方法

c - 如何在 C 中创建和读取数据类型的动态数组?