Question

I'm learning C++ by reading forums and books so I'm kind of new to the programmer's world. So please don't hesitate to improve my code because I'm eager to learn !

I'm having a problem to access an array of structure that I passed to a function. Here's my code :

struct Comber
{   double real;
    double im;
    double mod;
};


int main (void)
{
struct Comber *Nmbr=NULL;   //Nmbr Initialised for passing to Read where it's re-declared
int N;
Read(Nmbr, N);
Module(Nmbr, N);
}



void Read (Comber *Nmbr, int &N)
{

    cout<<"\nHow many of those numbers do you have ?\t";
    cin>>N;
    Nmbr = new struct Comber [N];

    for(int i=0;i<=N;i++)
    {
        cout<<"#"<<i<<"\nreal :\t";
        cin>>Nmbr[i].real;
        cout<<"img :\t";
        cin>>Nmbr[i].im;
        cout<<"-----"<<endl;
    }
}



void Module (Comber *Nmbr, const int &N)
{
    for(int i=0;i<N;i++)
    {
            //Here's where my problem is at.
        Nmbr[i].mod=sqrt(pow(Nmbr[i].real,2)+pow(Nmbr[i].im,2));
    }
}

I get an access violation because there's either no data stored or I'm looking at the wrong place. (right ?) So I'm wondering whether the mistake is in Read or in Module and what actually is.

Thanks for looking into it !

Was it helpful?

Solution

If you want to change the value of the Nmbr pointer, you need to pass it by reference or pointer, not by value. Like this:

void Read (Comber *&Nmbr, int *N)

With your code Nmbr in the main is not chaged.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top