函数引用结构对象的分段错误(核心转储)

问题描述 投票:0回答:0

我目前正在做一个项目,对指针和

struct
对象不熟悉。一切顺利,但我遇到了障碍,即分段错误(核心转储)错误。这是我正在使用的代码:

void battleInitiation(){
    int outcomeChoice = 0;
    int pOneATKRoll = battleRoll(8) + battleRoll(8) + p1.armySkill * 2 + p1.weaponComplexity * 3 + p1.armies;
    int pTwoATKRoll = battleRoll(8) + battleRoll(8) + p2.armySkill * 2 + p2.weaponComplexity * 3 + p2.armies;
            
    cout << "What is your goal for battle?\n";
    cout << "1. Devastate\n";
    cout << "2. Conquer\n";
    cin >> outcomeChoice;
    
    cout << "A fight ensues!\n\n";

    switch (outcomeChoice){
        case 1:
            weaponFailure(&p1);
            weaponFailure(&p2);

            if (pOneATKRoll > pTwoATKRoll || p2.weaponFailure){
                cout << p1.name << " has devastated this territory.\n\n";
                
                p2.territories--;
                p2.money -= rand()%750 + 500;
            }
            else if (pOneATKRoll == pTwoATKRoll || (p1.weaponFailure && p2.weaponFailure)){
                cout << "It's a tie!";
                
                p1.territories--;
                p1.money -= 5;
                p2.territories--;
                p2.money -= 5;
            }
            else if (pOneATKRoll < pTwoATKRoll || p1.weaponFailure){
                cout << p2.name << " has devastated this territory.\n\n";
                
                p1.territories--;
                p1.money -= rand()%750 + 500;
            }
        break;

此外,这里是 p1 和 p2 对象引用的

struct

struct Player {
    string name = "";
    int territories = 1;
    int armies = 10;
    int armySkill = 0;
    int armyEndurance = 0;
    int weaponComplexity = 0;
    int passiveIncome = 0; 
    int money = 50000;
    bool weaponFailure = false;
} p1, p2;

经过一些测试,我相信它是第一个 if 语句,我尝试的一些事情是在每次使用时使用 p1 和 p2 对象的内存地址,以及 p1 或 p2 对象的取消引用。此外,我尝试将 p1 和 p2 对象作为参数放入 battleInitiation() 函数中,但这也无济于事。它仍然是一个一致的分段错误(核心转储)错误。

例子:

&p1 vs p1
*p1 vs p1
battleInitiation(Player p1, Player p2)
c++ object pointers struct segmentation-fault
© www.soinside.com 2019 - 2024. All rights reserved.