简体   繁体   中英

How to add to object array pointer c++

I'm trying to add an object to an object array passed as an argument. Specifically, I have an array of buttons and I am adding a back button to the button array. How can I correctly do this? When I try the code below I get some weird glitches with the buttons passed from the original pointer array.

int createMenu(Button buttons[], int size)
{
    //Stuff here
}

int menu(Button buttons[], int size, bool back)
{
    Button * newButtons[size + 1];
    for (int i = 1; i <= size; i++)
        *newButtons[i] = buttons[i];
    Button back(25, 19, "Back"); //Creates back button object
    *newButtons[0] = back;
    return createMenu(*newButtons, size + 1);
    //Makes menu with the back button
}

Any help is appreciated.

In your loop you reference buttons[size], which is ouside of its bounds. You also dereference members of newButtons without initializing them. And you try to pass createMenu an array of pointers, when it expects an array of buttons. Should be something like this:

int menu(Button buttons[], int size, bool back)
{
    Button * newButtons = new Button[size + 1];
    for (int i = 0; i < size; i++)
        newButtons[i + 1] = buttons[i];
    newButtons[0] = Button(25, 19, "Back");
    int result = createMenu(newButtons, size + 1);
    delete [] newButtons;
    return result;
}

For reference, here's how it would look if you were using vectors:

int menu( std::vector<Button> buttons )
{
    buttons.push_back( Button(25, 19, "Back") );
    return createMenu( buttons );
}

If the button really needs to be pushed at the front then there are various options (eg actually push it at the front; or use a deque instead of a vector).

Try this. You are using Button*, so pass address of the Button object.

int menu(Button buttons[], int size, bool back)
{

    Button ** newButtons = new Button*[size + 1];
for (int i = 1; i <= size; i++)
        newButtons[i] = &buttons[i];
    Button * back = new Button(9,11,"fdf"); //Creates back button object
    newButtons[0] = back;

    //Makes menu with the back button
createMenu(*newButtons, size+1);
}

void createMenu(Button buttons[], int size)
{
    (buttons[0]).foo();

    //Stuff here
}

Also, you are using the same variable name "back" both as bool and as object of Button class. Change that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM