将数字输入动态数组

Input numbers into dynamic array

我希望我的程序让用户将数字输入动态数组,如果用户键入 -1,它将停止要求更多数字。这里的问题可能是我while的状态,这是我有疑惑的地方。

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));

}

您可能不想比较 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);

size=0; 以一个长度为 0 的数组开始,您在递增 size 之前用 scanf("%f", &v[i]); 写入 越界 。每次迭代都会发生相同的越界写入。我这样重写了。请注意,没有初始 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