1

So I am just making a quick game to help me understand programming in c++. Basically I made a pointer to a struct called player1 in the main method. After I initialized it and gave it some memory to use I decided to make a method to display the values of this specific pointer. Now I think this just shows that maybe I don't understand pointers like I should but When I try and access the pointer that I made in main it doesn't exist. in code i should be able to type player1->health to get the health in the method, but player1 doesn't exist in the methods scope.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

typedef struct enemy{
    char name[120];
    float health;
    int magic;
    int level;


} ene;

typedef struct player{
    char name[120];
    float health;
    int magic;
    int level;
    int exp;


} play;

void startGame();
void saveGame();
void displayHud();



int main(int argc, const char * argv[]) {
    // insert code here...
    // check if there is a save game
    // check if save game

    // initailize the player with 100 health and magic
    play *player1;

    player1 = (play *) malloc(sizeof(play));

    player1->health = 100;
    player1->level = 0;
    player1->magic = 100;
    displayHud();




    startGame();



    free(player1);
    return 0;
}



void displayHud(){
    printf("Health: %d Magic: %d Exp: %d", player1->health); //Doesn't exist


}
devin
  • 368
  • 1
  • 3
  • 19
  • Please have a look at this [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) list. And loose those C-like bad practices. – Ron Feb 10 '18 at 20:21

1 Answers1

1

Your code is C, not C++.

The compiler is right, player1 only exists in the main function. If you want to access it in displayHud you have to pass it as a parameter.

This is nothing at all to do with pointers, it's just the normal rules that apply to all variables in C (and C++).

Do this

void displayHud(play *player);

int main(int argc, const char * argv[]) {
    play *player1;
    ...
    displayHud(player1);
    ...
}

void displayHud(play *player) {
    printf("Health: %d Magic: %d Exp: %d", player->health);
}

This is very basic stuff, you probably should read a good book.

john
  • 85,011
  • 4
  • 57
  • 81
  • thank you its not my day today. I knew this I just for some reason didn't think of it. Thank you – devin Feb 10 '18 at 20:41
  • and everyone has a starting point sorry I don't amass knowledge as good as yourself – devin Feb 10 '18 at 20:45
  • btw @john this code produces an error "no matching function for the call display hud" – devin Feb 10 '18 at 21:07
  • @DevinTripp Did you remember to change the function prototype? That error message means that you prototype and your call don't match. – john Feb 11 '18 at 08:26