give feedback on this pointer program

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)


-------------Problems Reply------------

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

You are not initializing your array correctly. This statement:

double *array = new double(SIZE);

Allocates one double and initializes it to the value of SIZE. What you should be doing is using array allocation:

double *array = new double[SIZE];

Another general problem is you rarely ever want to assign dynamically allocated memory to a raw pointer. If you want to use base types instead of higher level objects such as std::vector, you should always use a smart pointer:

boost::scoped_array<double> array(new double[SIZE]);

Now the array will automatically get freed regardless of how you leave your scope (i.e. from a newly added return or from an exception).

Since we're talking about C++, I would suggest using STL containers and algorithms. I also find that in most cases it's better to use references or smart pointers (e.g. boost::shared_ptr) instead of raw pointers. In this case there's no need for pointers at all.

Here is how you could write your program:

#include <fstream>
#include <vector>
#include <iostream>
#include <numeric>
#include <iterator>

using namespace std;

int main()
ifstream f("doubles.txt");
istream_iterator<double> start(f), end;
vector<double> v(start, end);

if (v.empty())
cout << "no data" << endl;
return 0;

double res = accumulate(v.begin(), v.end(), 0.0);
cout << "Average: " << res / v.size() << endl;
return 0;

If x is 0, then Average will generate a divide-by-zero error.

Here are some "code review" comments:

In main():

  1. Change SIZE to "size_t" instead of int
  2. Why SIZE is uppercase? (May be the author's convention is to have constants as uppercase, in that case it is fine.)
  3. Combine temp declaration and assignment into one statement as: double * temp = array;
  4. What if inFile is not available or can't be opened for reading?
  5. What if inFile have less than SIZE number of items?
  6. Change the loop variable i to size_t.
  7. Remove blank line before declaration of inFile.
  8. Return some number (e.g. 0) from main().
  9. Correct the allocation of array.

In Average():

  1. Change the second argument of Average to size_t.
  2. Assert and/or guard for pointer being non-NULL
  3. Assert and/or guard against division by zero.

Acknowledgement: Some points are collected from other answers. I tried to make a complete list as far as I could.

Category:c# Views:1 Time:2010-05-06
Tags: c# pointers

Related post

  • Enable Smiley or Frown to give feedback in Office 2013 program. 2012-06-29

    Split from: I have office 2013 on my tablet and I don't see it. How do you activate it again?

  • Static and speaker feedback in web cam programs in Win7 2014-12-06

    recently had to redo my system and changed to Win7 pro 64-bit (from vista pro). I did a complete new install. All systems appear to be a go right now, though when i use web cam video chat programs my speakers produce loud static & feedback so as

  • Would like feedback on my PHP programming & advice on sessions 2010-08-13

    Hey I'm new to PHP so would really like your insight on how I'm programming and also I'm having trouble coming up with a solution for a session problem. I'm making a script for a bartering and Local Trade System (LETS) and I'm currently coding the of

  • How can i transfer data from an android device to a C++ PC program? 2012-01-23

    I want to connect an android mobile program to a C++ program, and i dont really know how it should be done. I was thinking about a Bluetooth connection, but i dont really know how to handle bluetooth in C++. Could you give me some general advice abou

  • Default installed program directory 2012-06-01

    new installed programs default directory changed from c/program files to c/windows/sys32/config/system profile/App data/local/ I am using windows 7, I realized the up stated problem .user profile service could not be started ,I also noticed missing i

  • WinfastPVR2 , tv card program is not working on windows 7 . I have a picture on tv but audio is missing!. 2013-05-23

    winfastPVR2 , tv card program who is working on service pack 2 - perfect ! now is not working on windows 7 . I have a picture on tv but audio is missing! I try to download an audio driver from net but i don't have any results, situation is same ! i n

  • "There was a problem sending the command to the program" when I try to open an attached Excel file in Yahoo or Gmail 2013-10-23

    This started since last month. Everytime I tried open an attached Windows Office EXCEL workfile in my yahoo or gmail , the following ERROR message occurs. "There was a problem sending the command to the program" Would be grateful if any expert out th

  • Why adding a Dragon program to this computer; blocked after posted? 2014-10-17

    Windows 7 Usage new program. --------------Solutions------------- Dragon program on this computer secured as it was completed. [Moved from feedback] Allow Microsoft programs to answers all question; and describe objectionable are made. [Moved from fe

  • Procedure for installing programs on win 7 x64? 2014-11-25

    I am getting a new win 7 x64 machine soon. I am intimately familiar with xp pro - and are extremely pc-literate. Is the following the best method for installing porgrams on the new machine - 1. If the 32x program has an .exe install file - - Run comp

  • Nokia 1020 Windows Developer Program 2015-01-18

    I joined the windows phone developer program so I could get the latest version for my phone. Where do I go to post feedback specifically for that program. Can't seem to find the site easily --------------Solutions------------- Hi there. Information a

  • A Nero program requires MICROSOFT. NET Framework 3.5. Where can I obtain this? 2015-02-24

    During set up for a Bundled Nero program it requires MICROSOFT. NET Framework 3.5 to allow installation where can I obtain this Thank you Moved from feedback Original title: Program Programs Compatibility Application Applications --------------Soluti

  • Should unauthorized actions in the UI be hidden, disabled, or result in an error? 2008-12-16

    This is a perennial question for me that I've never really resolved so I'd like your input. If I have actions that I know a user will not be able to perform due to insufficient privileges or object state, should the UI elements for those actions be h

  • Realistic time estimates for progress bars etc 2009-03-27

    I know I am not the only one who does not like progress bars or time estimates which give unrealistic estimates in software. Best examples are installers which jump from 0% to 90% in 10 seconds and then take an hour to complete the final 10%. Most of

  • Force mail client to use text rather then HTML through mailto: 2009-08-25

    I'm using SubVersion and TRAC on a C# project I am working on, and I have my TRAC system setup with a email address that can be used to create tickets. In my program I've added a simple "FeedBack" button in my program which sends an email to this add

  • .Net Thread.Suspend is obsolete. Looking for an alternative 2010-02-12

    I did some research and looking around and it seems the way to do this is using an AutoResetEvent. I quickly put this together and it seems to work and seems to be thread-safe. Can I have some feedback? class Program { private Thread workerThread; pr

  • Social networking APIs and C/C++ 2010-06-22

    Folks, Note sure if this is the best place to ask this one, but I doubt there'd be a better place. I see that github, stackoverflow, facebook, twitter, linkedin etc. have been providing developer API to slice and dice user information. Couple of ques

  • Give wrong GPS coordinates at first time 2010-06-26

    hi to all i want to know why location manager in iphone gives wrong coordinate at first time when run application.Due to this my distance is come 100 meter at start of application and my average speed is also effected due to this --------------Soluti

  • Invoke slot method without connection? 2010-07-21

    I have a live object implemented in the following way. It is used to execute long tasks in background. The main thread invoke the tasks by sending a signal to the public slots (i.e. doTask). Here is a stripped down example (not tested). class MyTask

  • Python and subprocess input piping 2010-11-02

    I have a small script that launches and, every half hour, feeds a command to a java program (game server manager) as if the user was typing it. However, after reading documentation and experimenting, I can't figure out how I can get two things: 1) A

Copyright (C), All Rights Reserved.

processed in 0.211 (s). 11 q(s)