簡體   English   中英

C程序崩潰,使用雙類型可變長度數組

[英]a C program crashes, using a double-type variable length array

我現在正在閱讀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".

我試圖消除使用可變長度數組,該程序似乎工作正常。 但我仍然無法得到原來的錯誤。

分配num時,大小為0。 您稍后會遇到訪問沖突,因為您嘗試訪問尚未分配的num [0]。

編輯:我建議使用動態內存或在讀取大小后聲明num。

把法規double num[size]; 從用戶輸入大小變量的大小后。

The program works fine when the "size" varialbe is less than 5.這是最危險的編程錯誤 - 一個似乎工作正常,但實際上沒有。 通過寫入您的數組,您可以立即寫入因某些其他目的而聲稱的內存,因為您的數組根本沒有長度。 您不能通過在事后更改size變量來更改數組的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值,盡管你可能稍后再次讀取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 Failed\n");
  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()是正確的方法。 除此之外,你可以讓你的數組大小任意大,並在它滿了后停止接受輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM