Struct and pointers

I have a problem when insantiating a struct. As I am a beginner at this, perhaps someone could be so kind to help me.

I have created a struct with:

struct MsgParameters
      CString msgName;
      int nrParams;
      CUIntArray params;

I then create instances of the struct with:

struct MsgParameters *messages[2];

I then try to use the struct with:

messages[0]->msgName = "Heartbeat";
messages[0]->nrParams = 1;
messages[1]->msgName = "Logon";
messages[1]->nrParams = 5;

When I do the 'messages[0]->msgName = "Heartbeat";' line I get an ACCESS VIOLATION. Why is that?? The msgName field is a string, so shouldn't I allocate the variable this way?

I Use Visual C++ 6.


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You have not allocated the memory for

messages[0] or messages[1]

Before you assgn anything do something like

messages[0] = new MsgParameters;
iarla, you are correct, though not very detailed, you probably should answer.

When you declare something like

struct MsgParameters messages[2];

 (which is NOT what you did), you are allocating space for 2 MsgParameters structures.  Now these structures will be uninitialized, but to initialize them you could do

messages[0].msgName = "heartbeat"

But instead you did

struct MsgParameters *messages[2];

Which also allocates space for two things.  But in this case the "things" aren't you structures they are pointers to you structures, i.e you have not made room for teo "MsgParameter"'s, but for two "MsgParameter *" 's.  So you now have 2 uninitialized pointers.  These need to be made to point to MsgParameter structures (or be made NULL).  One way to do so is what iarla showed you, though there are others depending on you need.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MDHAuthor Commented:
I give you the points since you explained it to me.. Thanks!
Thank you.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.