Can't write calculated resulted to file in C++

  • Context: Comp Sci 
  • Thread starter Thread starter madtraveller
  • Start date Start date
  • Tags Tags
    C++ File
Click For Summary

Discussion Overview

The discussion revolves around a C++ programming issue related to writing calculated results to a file in the context of a space transform function for a linearized convection-diffusion problem. Participants explore the technical aspects of array indexing and performance considerations in C++.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • madtraveller describes an error encountered when attempting to write results to a file, specifically mentioning a "memory could not be read" error.
  • Some participants point out that arrays in C and C++ are zero-based, indicating that valid indices for the "transfer" array range from 0 to 49, while madtraveller's loop runs from 1 to 50.
  • Suggestions are made to adjust the for loop to iterate from 0 to n-1 to avoid accessing out-of-bounds indices.
  • madtraveller acknowledges the advice and confirms that the suggested changes resolved the initial problem.
  • A later post raises a question about the performance difference between using the pow() function and simple multiplication for calculating powers.
  • Some participants argue that using a * a * a is faster than pow(a, 3) due to the overhead of the pow() function, while also cautioning against premature optimization that could affect code readability.
  • Another participant notes that pow() is not ideal for numerical programming in C and C++, suggesting that it is less efficient than direct multiplication.

Areas of Agreement / Disagreement

There is agreement on the indexing issue and the solution provided, but there are differing opinions on the use of pow() versus multiplication, with some participants advocating for the latter while others caution against micro-optimizations.

Contextual Notes

Participants discuss the implications of array indexing and performance considerations without reaching a consensus on the best practices for optimization in C++. The discussion reflects varying levels of emphasis on code readability versus performance.

Who May Find This Useful

Readers interested in C++ programming, particularly those dealing with numerical methods and performance optimization, may find this discussion relevant.

madtraveller
Messages
28
Reaction score
0

Homework Statement



Dear physics forum,

I'm start learning C++ and I'm trying to program a space transform function for linearized convection-diffusion problem using Code:block
Everything was fine until I wrote calculated result into a file. When I run the program, some error message popped up which related to "memory could not be read" and std::ostream::sentry::sentry() in debug windows

Code:
#include <iostream>
#include <fstream> // for working with file
#include <cmath>
#include <iomanip>
#include <stdio.h>
#include <math.h>
#include <cstdlib> // for exit function

using namespace std;

// Function for calculating exponental part of transfer function //
double  expo(double dx, double celerity, double time, double dif)
{
    double result;
    result = -(dx - celerity * time );
    result = exp ( pow (result, 2.0) / ( 4.0 * dif * time ));
    return (result);
}

// Main program
int main ()
{
    // Creat a file to store the result
    ofstream outdata;
    outdata.open ("Result.txt", ios::out);

   if( !outdata ) {                                     // file couldn't be opened
      cerr << "Error: file could not be opened" << endl;
      exit(1);
   }

    outdata << "OK??" << endl;

    // Declare variables
    double  PI = 3.14159,
            u  = 1.5,
            c,
            D  = 50.0,
            diffu = 0.0,
            t,
            t0 = 0.0,
            deltat = 1.0,
            deltax = 0.5;

    // Introduce number of interval
    int     n  = 50;

    // Create an array to store results of transfer function
    double  transfer[50] = {0.0};

    // Approximate c by u
    c = 5.0/3.0 * u;

    cout << "Time" << setw (21) << "Transfer function" << endl;

    // Loop for calculating transfer function
    for (int i = 1; i <= n; i++) {
        t = t0 + deltat * i;
        transfer[i] = deltax / ( 2.0 * sqrt( PI * D * t ));         // Calculate convection part
        diffu = expo(deltax, c, t, D);                              // Calculate diffusion part
        transfer[i] = transfer [i] * diffu;                         // Put 2 parts together

        cout << setw(2) << t << setw(18) << transfer[i] << endl;    // Print out results
    }

    for (int i = 1; i <= n; ++i) {
        outdata << transfer[i] << endl;
    }

    outdata.close();

    // Terminate the program
    return 0;
}


Homework Equations



T(t,deltax) = \frac{deltax}{2\sqrt{\Pi*D*t^{3}}}*e^{-\frac{(deltax - c*t)^2}{4*D*t}


Plz help me with this. Thank you very much for your time

Regards,

madtraveller
 
Physics news on Phys.org
Arrays are index from 0 in C and C++. The valid indices into the array "transfer" are 0 to 49. You are setting and then accessing elements 1 to 50.
 
Your for loop runs from i = 1 to 50, and your transfer array is declared to have 50 members.

In C and C++, arrays are zero-based, which means that the elements of your array are transfer[0], transfer[1], ..., transfer[49]. Your for loop is attempting to write to transfer[50], which is outside your array. I believe that's what is causing your problem.

Change your loop as follows
Code:
for(i = 0; i < n; i++)
{
   // body of loop
}
 
You guys are absolutely right! This solves my problem now !

Thank you again !

Regards,
 
Mark44 said:
Change your loop as follows
Code:
for(i = 0; i < n; i++)
{
   // body of loop
}

Even better, use
Code:
for(i = 0; i < n; ++i)
{
   // body of loop
}

In this case use of post-increment versus pre-increment doesn't really matter. However, as soon as you start using iterators, the post-increment operator can be quite expensive compared to the pre-increment operator. In C it is fairly standard to use post-increment by default, deferring the use of pre-increment as a signal that the programmer is being tricky. In C++ it is the other way around.
 
Could you also tell me which one is better:

pow (a, 3) or a * a * a

Thanks

Have a nice day every1

madtraveller
 
well of course a*a*a will be faster since it does not have to deal with the general case in pow(). Micro optimizing like this is rarely needed and when it does it is a last move optimization that is carefully profiled. If your you really want to optimize your code here's a few things to try to accomplish:

write better algorithms,
reduce dynamic memory (when possible),
improve access to readable/writable data,
ect..

Trying to micro optimize your code at such a level will actually cause a decrease in code readability, which is a bigger con than having a minimal optimization
 
madtraveller said:
Could you also tell me which one is better:

pow (a, 3) or a * a * a
Unfortunately, it is a*a*a. C and C++ lack an exponentiation operator and the pow() function is a very poor substitute for it. With most compilers, pow(a,3) is equivalent to exp(3*log(a)). This is one of the two key issues that makes some Fortran programmers think that C and C++ are terrible languages for numerical programming.
 
Thank you guys for your info.

MT
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 15 ·
Replies
15
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K