Link to home
Start Free TrialLog in
Avatar of daniel_bigham
daniel_bigham

asked on

Array of objects

The following code gives me an error:

      string* a;
      a = (string*) malloc( sizeof(string) * 10 );
      a[5] = "hehe";

What am I doing wrong?
Avatar of KurtVon
KurtVon

You are just making space for the string, you have not actually created a string object.  Try

a[5] = new string;
a[5] = "hehe";

Hope this helps.
Avatar of daniel_bigham

ASKER

Your suggestion doesn't work, since "new string" returns a pointer to a string, but a[5] is an actual string (not a pointer to a string).

the problem is that

string* a; means that a is a pointer and because of that you can access it as a pointer

but you're not allowed to use the operator[] on a pointer................

you can just use the * or -> operators

Apart from that, I guess that the posted code is just too ackward..........

why don't you try with

string a[5];
a[4] = string( "hehe" );

Hope this helps

Tincho
ASKER CERTIFIED SOLUTION
Avatar of blahpers
blahpers

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Great work blahpers! Thanks!