user3502486
user3502486

Reputation:

Array and Pointers - runtime error

I wrote a program for my assignment that involves pointers and dynamic allocation for an array, I am getting a runtime error and the program crashes, there are no compiling errors. Here is the program :

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

Sample Output :

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

Crashes here

Can someone let me know what the problem is with the PrintArray function?

Upvotes: 1

Views: 617

Answers (2)

songyuanyao
songyuanyao

Reputation: 172884

The parameter array of readArray() is passed by value, so array in main() remains NULL even if you changed it in readArray(). To make it be passed by reference. In addition, size doesn't need be passed by reference.

change

void readArray(float* array, int &size)

to

void readArray(float*& array, int size)

Upvotes: 2

paulsm4
paulsm4

Reputation: 121609

Q: Can someone let me know what the problem is with the PrintArray function?

A: Your PrintArray function is fine.

The problem is that you never pass the array you've allocated outside of readArray.

BETTER:

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);
   ...

NOTES:

  • If you declared a prototype for readArray() in array.h, you'll need to update it.

  • There are many ways to accomplish this, but the basic problem is you need ** (a pointer to a pointer) instead of * if you allocate your array inside the function. I believe passing the array pointer back as a function return is arguably the cleanest solution.

IMHO...

Upvotes: 2

Related Questions