I don't understand this... C++ question

Status
Not open for further replies.

yugpatel

Senior member
Feb 28, 2001
506
0
76
Code:
int main()
{
    balance* p;
    char s[80];
    double n;
    int i;
    try {
        p = new balance[3]; //allocate entire array
        } catch (bad_alloc xa){
            cout << "Allocation failure..." << endl;
            return 1;
        }
        //note use of dot, not arrow operaors
        p[0].set(12387.87, "Ralph Wilson");
        p[1].set(144.00, "A. C. Conners");
        p[2].set(-7.87, "I. M. Broke");

        for(i=0; i < 3; i++){
        p[i].get_balance(n,s);
        cout << s << "'s balance is: " << n << endl;
        }

        delete [] p;
    return 0;
}

I am confused about p[0].set(...). If p is a pointer to an array, how come -> gives compilation error. Can any one please clarify me?

I'll lock the thread because OP requested a delete, but I restored the original question because it had already been answered by the time OP deleted it.

Markbnj
 
Last edited by a moderator:

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
p = pointer to array
p[ n ] = the nth element of the array. It's the object pointed to, not a pointer. It's already dreferenced by [] like you do with *p for a single value.

p[ n ] = *( p + n * sizeof(type p points to) )
 
Status
Not open for further replies.