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?
LVL 1
daniel_bighamAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
blahpersConnect With a Mentor Commented:
All close but not quite.

The poster is trying to dynamically create an array of ten strings and assign the sixth a value of "hehe".

string* a = new string[10];
a[5] = "hehe";
// ... other code here ...
delete [] a;

Of course, STL would discourage you from using pointers--try the following instead:

vector<string> a(10);
a[5] = "hehe";
// ... other code; no need to delete

malloc() and free() have limited usefulness in C++; use them only if necessary, as they circumvent all class mechanisms (such as con-/destructors).
0
 
KurtVonCommented:
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.
0
 
daniel_bighamAuthor Commented:
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).

0
 
tinchosCommented:
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
0
 
daniel_bighamAuthor Commented:
Great work blahpers! Thanks!
0
All Courses

From novice to tech pro — start learning today.