私は最近CPrimerPlusを読んでいます。これは、第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
「サイズ」バリアルベが5未満の場合、プログラムは正常に動作します。ただし、「サイズ」バリアルベに6以上の数値を入力すると、実行時にプログラムがクラッシュします。
大まかに翻訳すると、エラーメッセージは次のようになります。
the memory 0x00000038 used by 0x77c1c192 could not be "written".
可変長配列の使用を排除しようとしましたが、プログラムは正常に動作しているようです。しかし、私はまだ元のもののどこが間違っているのかを知ることができませんでした。