0

I am new to pointers and I am having trouble in accessing the variables inside a class.

I want to make a sort of database of possible moves in a Chess game, and I think that using pointers is the way to go, since I wouldn't be wasting memory and prevent any unnecessary memory errors.

main.cpp

#include <iostream>
#include "moves.h"

using namespace std;

int main()
{
    moves* possibleMoves[100];
    &(possibleMoves[0]->piece) = 100;
    cout << *&possibleMoves[0]->piece << endl;
    return 0;
}

moves.h

#ifndef MOVES_H
#define MOVES_H


class moves
{
public:
    moves();
    int piece;
    int X;
    int Y;
    int addX;
    int addY;
    int score;
};

#endif // MOVES_H

Any help would be appreciated. Thank you very much in advance.

Currently it doesn't output anything and I don't know what to do.

  • You seem to be in a lot of confusion about `&` and `*` and pointers in general. Better pick up a [beginners book](https://stackoverflow.com/questions/388242) before asking, as this will probably just receive downvotes. – Henri Menke May 27 '18 at 04:17
  • Yeah, I'm sorry. Thanks for the advice. I forgot to remove the & and *. I was just too frustrated at why it wasn't working so I just put them together with no regards to anything whatsoever. – Richard Escobia May 27 '18 at 04:30
  • 2
    "I think that using pointers is the way to go, since I wouldn't be wasting memory and prevent any unnecessary memory errors." Using unnecessary pointers and dynamic memory will do the exact opposite of what you want. Do you really need pointers? Have you considered using standard library containers? – eesiraed May 27 '18 at 04:45

2 Answers2

1

I am having trouble in accessing the variables inside a class

It looks like you are making a mess of pointers and references.

There isn't a real need in your code to use array of pointers. Instead using normal array of objects would do.

moves possibleMoves[100];
possibleMoves[0].piece = 100;
cout << possibleMoves[0].piece << endl;

Btw, class moves incorrectly exposes all data members to public - they should be private. And moves constructor needs to be implemented or otherwise should be removed to use the default one.

artm
  • 17,291
  • 6
  • 38
  • 54
0

You are creating an array of pointers with:

   moves* possibleMoves[100];

when what you want is an array of moves.

Then you are trying to assign piece in possibleMoves[0] a value of 100 with:

   &(possibleMoves[0]->piece) = 100;

but you are actually doing something quite different. As @Henri Menke said best to read up on &, *, . and ->.

To make your intended code work try:

int main()
{
    moves possibleMoves[100];
    possibleMoves[0].piece = 100;
    cout << possibleMoves[0].piece << endl;
    return 0;
}

Here you create an array of moves objects, then assign the value of piece in object 0 a value of 100. You retrieve the value and print it to cout.

mjc449
  • 114
  • 1
  • 9