【问题标题】:Array and Pointers - runtime error数组和指针 - 运行时错误
【发布时间】:2014-04-06 00:07:07
【问题描述】:

我为我的作业编写了一个程序,其中涉及数组的指针和动态分配,我收到运行时错误并且程序崩溃,没有编译错误。这是程序:

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;
}

ma​​in.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 函数有什么问题?

【问题讨论】:

    标签: c++ arrays pointers dynamic


    【解决方案1】:

    readArray() 的参数array 是按值传递的,所以main() 中的array 保持NULL 不变,即使你在readArray() 中更改了它。使其通过引用传递。另外,size 不需要通过引用传递。

    改变

    void readArray(float* array, int &size)
    

    void readArray(float*& array, int size)
    

    【讨论】:

      【解决方案2】:

      问:谁能告诉我 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() 的原型,则需要对其进行更新。

      • 有很多方法可以实现这一点,但基本问题是如果在函数内部分配数组,则需要**(指向指针的指针)而不是*。我相信将数组指针作为函数返回传回可以说是最干净的解决方案。

      恕我直言...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-09
        • 2020-06-19
        • 1970-01-01
        • 2015-03-08
        • 2013-10-26
        • 1970-01-01
        • 2015-06-18
        • 2016-06-25
        相关资源
        最近更新 更多