【发布时间】:2012-05-31 10:39:17
【问题描述】:
这些天我正在阅读 C Primer Plus,这是我为第 10 章中的编程练习 No.4 编写的代码,查找双类型数组中最大数字的索引。我使用可变长度数组来手动指定数组大小:
#include <stdio.h>
int findmax(const double array[], int s);
//find the index of the largest number in the array
int main(void)
{
int size = 0; //size of the array
int index = 0; //index of the largest number
double num[size]; //the array holding double-type numbers
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter %d numbers: ", size);
for (int i = 0; i < size; i++)
scanf("%lf", &num[i]);
index = findmax(num, size);
printf("The index of the max number in the array is: %d\n", index);
return 0;
}
int findmax(const double array[], int s)
{
int index = 0;
double max = array[0];
for (int i = 0; i < s; i++)
if (array[i] > max)
{
max = array[i];
index = i;
}
return index;
}
这段程序编译正常,使用MinGW(假设程序文件名为prog.c):
gcc prog.c -o prog.exe -std=c99
当“size”变量小于 5 时程序运行良好。但是当我为“size”变量输入 6 或更大的数字时,程序在运行时崩溃。
翻译松散,错误信息是:
the memory 0x00000038 used by 0x77c1c192 could not be "written".
我试图消除可变长度数组的使用,程序似乎工作正常。但是我还是不知道原来的哪里错了。
【问题讨论】:
标签: c arrays floating-point double variable-length