0

I'm using raylib to make a little game. and here is the problem.

Struct Icon has Loc Struct that has two integer value.

When i put the Struct, Icon as a Pointer into Icons vector. value has been changed.

here is the capture of debuging.

enter image description here

enter image description here

and here is the full code.

// driver.cpp void init() { InitWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Uvuntu"); SetTargetFPS(30); map<string, Texture2D> mapset = loadAllImages(); setCursor(mapset.find("cursor")->second); setIcons({ "File Exploer", mapset.find("icon_dir")->second, nullptr }); setIcons({ "File Exploer", mapset.find("icon_dir")->second, nullptr }); runIcons(); } // icons.cpp using namespace std; vector<Icon*> icons; int default_x = int(WINDOW_WIDTH / 50); int default_y = int(WINDOW_HEIGHT / 50); int step = 128; int icon_x = default_x; int icon_y = default_y; void setIcons(Icon icon) { Loc loc = { icon_x, icon_y }; icon.loc = &loc; icon_y += step; if (icon_y > WINDOW_HEIGHT) { icon_y = default_y; icon_x += step; } cout << icon.loc->x << endl; cout << icon.loc->y << endl; icons.push_back(&icon); } void runIcons() { Loc loc = *icons.at(0)->loc; // the problem... string name = to_string(loc.x) + ", " + to_string(loc.y); cout << name << endl; } // icon.cpp using namespace std; struct Icon { string name; Texture2D icon_img; Loc* loc; }; // loc.cpp struct Loc { int x, y; }; 
6
  • 1
    why do you store pointers in the vector? icon is a local variable that ceases to exist when the function returns Commented Aug 22, 2022 at 12:54
  • 1
    icon.loc = &loc; is wrong for the same reason Commented Aug 22, 2022 at 12:55
  • Enable all warnings and use -Werror. Why should I always enable compiler warnings? Commented Aug 22, 2022 at 12:56
  • 1
    In C++, automatic storage duration, which is the storage of all local objects, the object is allocated at the beginning of the enclosing code block and deallocated at the end. What you want is dynamic storage duration, such as used by new; or better yet use std::make_unique<Icon> with your vector<std::unique_ptr<Icon>> icons;. Commented Aug 22, 2022 at 13:11
  • 2
    @Roharui -- void setIcons(Icon icon) -- Are you using another computer language as a model in writing C++ code? You are aware that passing variables this way in C++ makes a temporary copy of the variable? You are not working on the original Icon that was passed, only a copy. I know that other computer languages, that Icon is a reference to the original Icon that is passed, but that is not how C++ works. If you are using another language as a model in writing C++ code, don't. What you wind up with are 1) Buggy code, 2) Inefficient code, 3) Code that looks weird to a C++ programmer. Commented Aug 22, 2022 at 13:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.