0

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 !

2
  • 1
    Unrelated, but you really should be passing N by reference. This is C++ code that's written almost as though it's C. Commented Feb 15, 2014 at 21:16
  • 1
    Thank you for the advice. Just looked up what it means and it is indeed WAY simpler, and also better written I guess. Commented Feb 15, 2014 at 21:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah thanks a lot, it works (no kidding). ^^ Could you explain me how it really works. Was I overwriting the address of the array or what ?
@Moontail: the struct you create via 'new' was only stored in 'Nmbr' variable, which is local to 'Module()', so it was never stored in the array, as you intended. Have a look at pw1.netcom.com/~tjensen/ptr/pointers.htm to gain a better understanding :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.