将数字输入动态数组

时间:2015-12-13 18:16:07

标签: c arrays dynamic dynamic-memory-allocation

我希望我的程序将用户输入的数字转换为动态数组,如果用户输入-1,它将停止要求更多的数字。这里的问题可能就是我的情况,这就是我怀疑的地方。

int i=0, size=0;
float *v;
printf("Write a group of real numbers. Write -1 if you want to stop writing numbers\n");
v=(float*)malloc(size*sizeof(float));
while(v!=-1)
{

    printf("Write a number\n");
    scanf("%f", &v[i]);
    i++;
    size++;
    v=realloc(v, (size)*sizeof(float));

}

2 个答案:

答案 0 :(得分:1)

size=0;以0长度数组开头,在递增scanf("%f", &v[i]);之前,您将{em>越界写入size。每次迭代都会发生相同的越界写入。我改写了这样的话。请注意,没有初始malloc因为realloc在给出NULL指针时会起作用。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int size = 0, i;
    float *v = NULL;
    float val;
    printf("Write a group of real numbers. Write -1 if you want to stop writing numbers\n");
    printf("Write a number\n");
    while(scanf("%f", &val) == 1 && val != -1)
    {
        v = realloc(v, (size+1) * sizeof(float));
        v[size++] = val;
        printf("Write a number\n");
    }

    printf("Results\n");
    for(i=0; i<size; i++)
        printf("%f\n", v[i]);
    free(v);
    return 0;
}

计划会议:

Write a group of real numbers. Write -1 if you want to stop writing numbers
Write a number
1
Write a number
2
Write a number
3
Write a number
-1
Results
1.000000
2.000000
3.000000

答案 1 :(得分:0)

您可能希望将v-1进行比较,而不是将v[i - 1]-1进行比较。此外,您应该在scanf无法解析数字时执行错误检查:

do {
    printf("Write a number\n");
    if (scanf(" %f", &v[i]) != 1) {
        /* error handling here */
    }

    v = realloc(v, size * sizeof *v);
    if (v == NULL) {
        /* error handling here */
    }
} while (v[i++] != -1);