1

I want to make a pointer to an instance of a class. Many instances - that is why I made an array which saves all of those. But how can I set the value of a pointer in a class to 0? That is the code... Maybe you know what I'm talking about

public:
    CCharacter *pTeamMember[15];

And in another file:

pTeams[team]->pTeamMember = 0;

It causes following error.

error C2440: '=' can't convert 'int' into 'CCharacter *[15]

What I don't understand is, that this don't causes any errors:

public:
    Team *pTeams[31];

And in another file:

pTeams[i] = 0;

Does anyone have ideas?

4
  • what is CCharacter and Team? Commented May 15, 2014 at 14:13
  • sorry, try: pTeams[team]->pTeamMember[member] = 0; (member being the corresponding index) Commented May 15, 2014 at 14:15
  • Your first erroneous assignment attempts to assign an integral constant to an array. Arrays are not allowed as lvalues in an assignment expression. Their "value" is fixed (the address of the first element in the array) and cannot be changed. Your second example is allowed because you're assigning to a pointer residing in an array of pointers. This is the fundamental difference between pointers and arrays; Pointers hold addresses; arrays are addresses. Commented May 15, 2014 at 14:19
  • Don't use an array, use std::vector<CCharacter *> or even better, a vector of unique_ptr or shared_ptr. Commented May 15, 2014 at 15:52

2 Answers 2

1

pTeamMember isn't a pointer. It's an array of pointers-to-CCharacter.

In your second example, you're assigning to one of the pointers in the array. You could do the same with pTeamMember:

pTeams[team]->pTeamMember[i] = 0;
Sign up to request clarification or add additional context in comments.

Comments

0

To set the value of a pointer to 0 (presuming you mean point at nothing), you can do the following. Note that you can use 0 or nullptr (which is valid as of C++ 11)

int *p = nullptr;

In regards to your specific example, change

pTeams[team]->pTeamMember=0;

to

pTeams[team]->pTeamMember[index]=0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.