这些天我正在阅读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: %dn", 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
当"大小"变量小于 5 时,程序工作正常。但是当我为"size"变量输入 6 或更大的数字时,程序在运行时崩溃。
松散地翻译,错误消息是:
the memory 0x00000038 used by 0x77c1c192 could not be "written".
我试图消除可变长度数组的使用,该程序似乎工作正常。但我仍然无法理解原始版本的问题所在。
num 时大小为 0。稍后会出现访问冲突,因为您尝试访问尚未分配的 num[0]。
编辑:我建议使用动态内存或在读取大小后声明数字。
在从用户那里输入大小变量的大小后,将语句放在double num[size];
。
The program works fine when the "size" varialbe is less than 5.
这是最危险的编程错误 - 看起来工作正常,但实际上并非如此。通过写入数组,您可以立即写入为其他目的而声明的内存,因为数组根本没有长度。您不能只是通过事后更改size
变量来更改数组的大小。
一种选择是在声明数组之前确定size
。另一种是使用 new
执行动态分配,但我敢肯定,您将在几章中介绍这一点。
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);
当你第一次声明 num array
时,它的大小将为零,因为这是执行该行时的大小值,尽管您稍后可能会再次读取 size 的值。
当您创建数组时,数组的大小将为零,正如其他人已经指出的那样。因此,当您尝试将元素填充到数组中时,没有可用的内存,它会覆盖到其他内存中,最终导致内存损坏。
您可以按如下方式重写代码以避免此问题。
int size = 0; //size of the array
int index = 0; //index of the largest number
double *num = NULL; //Change it to a pointer
printf("Enter the size of the array: ");
scanf("%d", &size);
num = malloc(size * sizeof(double));
if(NULL == num)
{
printf("Malloc Failedn");
return 0;
}
printf("Enter %d numbers: ", size);
for (int i = 0; i < size; i++)
scanf("%lf", &num[i]);
或
int size = 0; //size of the array
int index = 0; //index of the largest number
printf("Enter the size of the array: ");
scanf("%d", &size);
double num[size]; //Now, num will have proper size
printf("Enter %d numbers: ", size);
for (int i = 0; i < size; i++)
scanf("%lf", &num[i]);
这是一篇关于 C99 可变长度数组的信息性文章的链接,该文章讨论了 C99 的可变长度数组可能导致的一些潜在问题。
正如其他人所建议的那样,使用 malloc() 是执行此操作的正确方法。除此之外,你可以把你的数组变成任意的大尺寸,一旦它满了就停止接受输入。