【问题标题】:Input numbers into dynamic array将数字输入动态数组
【发布时间】:2016-03-19 04:44:54
【问题描述】:

我希望我的程序将用户输入的数字变成一个动态数组,如果用户输入 -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));

}

【问题讨论】:

    标签: c arrays dynamic dynamic-memory-allocation


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      您可能想要比较v[i - 1] 和-1,而不是比较v 和-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);
      

      【讨论】:

        猜你喜欢
        • 2023-03-27
        • 1970-01-01
        • 2015-06-21
        • 1970-01-01
        • 2012-04-04
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多