簡體   English   中英

數組和指針-運行時錯誤

[英]Array and Pointers - runtime error

我為分配編寫了一個程序,該程序涉及數組的指針和動態分配,遇到運行時錯誤,程序崩潰,沒有編譯錯誤。 這是程序:

array.h:

#include <iostream>

using namespace std;

void readArray(float*, int &);
void PrintArray(float*, int);

array.cpp:

#include "array.h"

void readArray(float* array, int &size)
{
    array = new float[size];
    cout << endl;
    cout << "Enter the array elements, use spaces: ";
    for (int i = 0; i < size; i++)
    {
        cin >> array[i];
    }
    cout << endl;
}

void PrintArray(float * array, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << array[i] << " ";
    }
    cout << endl;
}

main.cpp:

#include "array.h"
int main()
{
    int size = 0;
    cout << "How many elements would you like to enter? ";
    cin >> size;
    cout << endl;
    float *array = NULL;
    readArray(array,size);
    cout << "The array size is " << size << endl;
    PrintArray(array, size);
    return 0;
}

樣本輸出:

How many elements would you like to enter? 3
Enter the array elements, use spaces: 4.0 5.0 6.0
The array size is 3

在這里崩潰

有人可以讓我知道PrintArray函數出了什么問題嗎?

問:有人可以讓我知道PrintArray函數出了什么問題嗎?

答:您的PrintArray函數很好。

問題是您永遠不會傳遞您在readArray之外分配的數組。

更好:

float * 
readArray(int size)
{
    float* array = new float[size];
    cout << endl;
    cout << "Enter the array elements, use spaces: ";
    for (int i = 0; i < size; i++)
    {
        cin >> array[i];
    }
    cout << endl;
    return array;
}


int main()
   ...
   float *array = readArray(size);
   ...

筆記:

  • 如果您在array.h中聲明了readArray()的原型,則需要對其進行更新。

  • 有很多方法可以完成此操作,但是基本問題是,如果在函數內分配數組,則需要** (指向指針的指針)而不是* 我相信將數組指針作為函數返回傳回是最干凈的解決方案。

恕我直言...

readArray()的參數array按值傳遞,因此即使您在readArray()readArray()更改, main() array仍為NULL 以使其通過引用傳遞。 另外, size不需要通過引用傳遞。

更改

void readArray(float* array, int &size)

void readArray(float*& array, int size)

暫無
暫無

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

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