【问题标题】:C Program doesn't continue to follow code in main() function after calling a function inside of it在调用 main() 函数内部的函数后,C 程序不会继续跟踪 main() 函数中的代码
【发布时间】:2020-08-07 10:40:55
【问题描述】:

不会在 main() 函数中执行以下代码。任何输入表示赞赏。附言我正处于创建井字游戏的初期阶段。

void printBoard(int slotNumber);

int main()
{
int slotNumberMain = -1;
printf("prints this\n");
printBoard(slotNumberMain);
printf("but not this\n");


return 0;
}

void printBoard(int slotNumber)
{

int boardSlots[3][3];
int i;
int j = 0;

for (i = 1; i <= 9; i++){
    char box[4] = {'[', ' ', ']', '\0'};
    boardSlots[j][i - 1] = i;

    if (slotNumber == i){
        char box[4] = {'[', 'X', ']', '\0'};
    }

    printf("%s", box);
    if (i % 3 == 0){
        j++;
        printf("\n");
        }
    }

}

编辑:有一个 slotNumber 变量的原因是因为最初我添加了一个 enterNumber() 函数(将在 printBoard() 的末尾调用,并让你输入一个数字并用'x标记框' 在调用 printBoard(slotNumberMain)) 之后,我没有在此处添加代码,因为我意识到问题完全在 printBoard() 和 main 中。)

编辑 2:我已经解决了这个问题,这是由于 boardSlots 数组像有人建议的那样被溢出。

感谢所有试图提供帮助的人。

【问题讨论】:

  • 想想i - 1 是否会超过 2。此外,调试器在这些情况以及更多情况下都有帮助,因此您应该为您的平台找到一个。
  • 超出boardSlots 数组后,其他一切都是未定义的行为。一个很大的可能性是它覆盖了堆栈上的返回地址,因此函数返回到其他地方。
  • 附带说明,if(slotNumber == i) 块不会做你想做的事;在该块内声明的char box[] 是该块的本地,并且与在外部块中声明的box 数组是分开的并且不会影响该数组。你的程序永远不会打印 X。
  • 请检查编辑,谢谢。
  • 您有两个名为 box 的变量,它们的生命周期重叠。这不是一个好习惯。

标签: c function main


【解决方案1】:

我已经解决了这个问题,这是由于 boardSlots 数组像有人建议的那样被溢出。

void printBoard(int slotNumber)
{

    int boardSlots[3][3];

    int i;
    int j = 1;
    char box[4] = {'[', ' ', ']', '\0'};

    for (i = 1; i <= 3 && j <= 3; i++){

        boardSlots[j - 1][i - 1] = i * j;

        if (slotNumber == i){
            char box[4] = {'[', 'X', ']', '\0'};
        }

        printf("%s", box);
        if (i == 3){
            j++;
            i = 0;
            printf("\n");
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多