Hello,
I am writing a section of c++. Here is the section that does not work:

int a, escape;
        double temp1,temp2;
        escape  = 0;
        a       = 0;

        while(escape < 2){
                Complex c[a];
                cout << "Please input a complex number, the real part follwed by the imaginary part.\n";
                if(!(cin >> temp1 >> temp2)){
                        return -1;
                }
                cout << "a is: " << a << "\n";
                cout << "Setting temp1 to: " << temp1 << "\t Setting temp2 to: "<<
 temp2 << "\n";

                c[a].setComplex (temp1, temp2);
                escape++;
                a++;
        }

I know a, escape, temp1, temp2 is behaving correctly. However, the assignment of c[a].setComplex is not working correctly. (setComplex works, and the classes work). After the while-loop, i've print the values of c[0] , c[1], and they are nothing like the values they should be.

I'm assuming that i'm using c[a] incorrectly, any ideas ? :) cheers

sorry, if this post isn't clear enough.

The Complex c[a] sets up storage for an array of Complex class/structure but doesn't create them. You'll have to create a complex object then assign it to the array.

The declaration

Complex c[a];

isn't valid C++, though some compilers will accept it.

Those that do will presumably take it to mean a request to define an array with "a" elements. Those elements will have indices ranging from 0 through a-1. When you subsequently execute

c[a].setComplex(temp1, temp2);

you will be trying to access the array element with index "a", which is out of bounds.

If that's not enough, consider that line 4 of your code sets "a" to 0, so when you define c in line 7, it will not have any elements at all. Therefore, any attempt to access an element of c will be out of bounds. So when you say that you're trying to access c[0], c[1], and so on, it doesn't surprise me that it doesn't work--none of those elements exist.

This article has been dead for over six months. Start a new discussion instead.