使用 if 语句更改指针的位置,C++

Mic*_*ney 1 c++ pointers chess

我对 C++ 很陌生。我的编译器是 g++ 12.2.0。

我正在尝试使用if语句来更改指针分配的内容。我不明白为什么在添加附加if语句时它会停止工作。问题在于*movingPiece,如果if(a==2){}被注释掉则没有问题。

bool checkMove(int a , uint64_t s , uint64_t e, bool colour, uint64_t board, uint64_t black, uint64_t white, uint64_t pawn, uint64_t king, uint64_t queen, uint64_t bishop, uint64_t knight, uint64_t rook , uint64_t attackMap , uint64_t doubleAttackMap)
{
    uint64_t x ,z , *movingPiece;
    uint64_t *pieces = &white;
    board = board &~ s;
    if (colour){ uint64_t *pieces = &black; }
    if (a == 0){
        //pawn
        uint64_t *movingPiece = &pawn;
        *movingPiece = *movingPiece &~ s;
    }
    if(a == 1){
        //queen
        uint64_t *movingPiece = &queen;
        *movingPiece = *movingPiece &~ s;
    }
    if(a==2){
        uint64_t *movingPiece = &rook;
        *movingPiece = *movingPiece&~s;
    }

    *pieces = *pieces|e;
//----------------------------------------Code executes up until this point
    *movingPiece = *movingPiece|e;
//----------------------------------------Code beyond does not execute
    board = board|e;
    generateAttackMap(~colour, board, black, white, pawn, king, queen, bishop, knight, rook, &x , &z);
    if (x & king){
        return false;
    }
    else{
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

我尝试过使用switch, 并在不同的位置分配变量,但所有结果都导致代码不执行。

预期指针会将修改后的变量传递到底部的代码块中,即 into attackMapGenerator。此代码用于检查移动是否会导致玩家在移动后受到检查。

我正在使用uint64_t64 位整数上的按位逻辑。

azh*_*en7 6

您在语句movingPiece内部声明if,因此创建了新变量,并且原始movingPiece变量不会被修改。没有内存地址被分配给原始movingPiece变量,这意味着它指向内存中的随机位置。当您尝试使用*movingPiece = *movingPiece|e修改指向的值时movingPiece,您正在访问不应该访问的内存。操作系统看到这一点并抛出分段错误,最终杀死程序,这就是为什么你的代码在该行停止执行。

if语句更改为:

if (a == 0){
    movingPiece = &pawn;
}
else if(a == 1){
    movingPiece = &queen;
}
else if(a==2){
    movingPiece = &rook;
} 
else {
    std::cerr << "invalid a\n";
    std::exit(1);
}
*movingPiece &= ~s;
Run Code Online (Sandbox Code Playgroud)