• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 332
  • Last Modified:

Creating Array of Structs.

I'm attempting to create an array of structs.  The struct name  "person" is defined in the .h, then in my constructor in my .cpp,  i have the following code:
      int index=10;
      person entry[index];

in actuality, the person entry[index]; will be in a while loop, as I dont know how many structs i need ahead of time.  When i go to compile, i get the following errors:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
'entry' : unknown size

Why isn't it reading my variable "index" size as 10?  Do i have to use DMA or something?..
Using Microsoft Visual C++ 6.0
1 Solution
Jaime OlivaresCommented:
by using c++ features you have the option to use the new operator, something likeƧ
person *entry;
entry = new person[index];

to delete use:
delete [] entry;

Consider that if you instatiate directly as you proposed in your constructor, array will be destroyed at return.
With my suggestion, you will need to put 'entry' variable as your app's member or as a global variable.

If you want fully dynamic arrays, then you can use vector<> template, another c++ feature.
I recommend you use CArray or std::vector instead.
These containers are much safer, because they'll automatically delete the contents in the container, and you can use the same syntax that you would use for a regular C-Style array.
Example code:

#include <afxtempl.h>

class person
      CString Name;

class foo
      foo(int size)
            m_ArrPerson[0].Name = "David";
            m_ArrPerson[1].Name = "Axer";
      CArray<person, person&> m_ArrPerson;

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now