简体   繁体   中英

C++ - passing data to struct

I'm translating a Fortran 77 code to C++ and the Fortran 77 uses common blocks. I am trying to replace the common blocks with structs which I will then fill with values from a function and then call both to be used in my main. At the moment my code looks like:

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

// data_list 
struct data_list {
    double g, dw, Vel, M, dt, N;
    int Ioutp1, Ioutp2; 
    } values;

void data (data_list& val) {
    val.g = 9.80665;
    val.dw = 0.05; 
    val.Vel = 20.0;
    val.M = 128; 
    val.dt = 0.05; 
    val.N = 4000;
    val.Ioutp1 = 1;
    val.Ioutp2 = 1;
    }   

void Pierson_Moskowitz(data_list& val) {

/*
* Calculation of properties of Pierson_Moskowitz Spectrum
*/
    double Ug, Hs, A, B, Std;
    cout << values.Vel << "\t\t" << values.g; 
    Ug = values.Vel/values.g;
    cout << Ug << endl;

}   
int main() {
  data(values);
  //float dw = values.dw = 0.05;
  cout << values.dw << endl; 

}

This is just a test as at the moment my main isn't doing anything except printing a value. What I want is for the variables that are given values in my data function to be able to be used throughout the code. At the moment, there are two things I'm confused about:

1) My Pierson-Moskowitz function isn't printing anything for Ug. I don't understand why not? 2) I'm not sure that I even need the data function. Essentially the Fortran code that I'm translating uses a subroutine to assign values to variables in a common block. I am trying to do something similar by using a struct and then a function to fill it with values.

This code is quite short and I plan to keep everything in one file. Any help is really appreciated!!

You want to pass in a reference to your common block:

void data (data_list& val) {

then you're changes will be to the common block rather than a copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM