Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

give feedback on this pointer program

Tags:

c++

pointers

This is relatively simple program. But I want to get some feedback about how I can improve this program (if any), for example, unnecessary statements?

#include<iostream>
#include<fstream>
using namespace std;

double Average(double*,int);

int main()
{

    ifstream inFile("data2.txt");

    const int SIZE = 4;
    double *array = new double(SIZE);
    double *temp;
    temp = array;

    for (int i = 0; i < SIZE; i++)
    {
        inFile >> *array++;
    }
    cout << "Average is: " << Average(temp, SIZE) << endl;
}

double Average(double *pointer, int x)
{
    double sum = 0;

    for (int i = 0; i < x; i++)
    {
        sum += *pointer++;
    }
    return (sum/x);
}

The codes are valid and the program is working fine. But I just want to hear what you guys think, since most of you have more experience than I do (well I am only a freshman ... lol)

Thanks.

like image 486
CppLearner Avatar asked Jan 20 '26 01:01

CppLearner


1 Answers

Fix the memory leak. i.e delete temp; Also, check if the file is open/created..etc

ideally, you should manipulate/traverse the array using your temp variable instead of using *array itself

like image 150
SysAdmin Avatar answered Jan 21 '26 15:01

SysAdmin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!