【问题标题】:Array contents are not displaying properly数组内容显示不正确
【发布时间】:2016-02-20 03:15:17
【问题描述】:

这里是 C 初学者,我有一个正在开发的程序,不幸的是,该程序要么没有正确读取数组,要么没有正确显示内容。

这就是我所拥有的

int main()
{
    int size;     // the number of elements 

    printf("Enter size of the array: \n");
    scanf("%d", &size);

    double *array = malloc(size*sizeof(int));  //memory allocated using malloc
    if (array == NULL)
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    printf("Enter elements of array: \n");
    for (int i = 0; i<size; ++i)
    {
        scanf("%d", &array[i]);
    }

    printf("Results:");

    double min = array[0]; 
    printf("\nmin = %.3lf ", min);
    double max = array[size - 1]; 
    printf("\nmax = %.3lf", max);

这是我的输出

【问题讨论】:

  • 您正在分配一个整数数组并将其分配给一个双指针。

标签: c arrays input output


【解决方案1】:

array = malloc(sizesizeof(int));

应该是:

double *array = malloc( size * sizeof(double) );

scanf("%d", &array[i]);

这里错误的控制字符串,应该是%lf for double,而不是%d

【讨论】:

  • 做到了,同样的事情还在发生
猜你喜欢
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多