这是一个程序,它从用户输入他的名字并从石头、剪刀、布中进行选择。它有一个函数
generateRandomNumber(int n)
可以生成 0、1 或 2。根据计算机分配的选择数字,比较两个选择,看看谁赢得了这一轮。如此重复3次,得分最高者获胜。但是在比较选择之前尝试打印计算机的选择时似乎存在分段错误。
我不明白这个错误背后的原因。请帮我修复代码。
源代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int generateRandomNumber(int n)
{
srand(time(NULL));
return rand() % n;
}
int main()
{
int num;
char PlayerName[50];
char Pselection[8], Cselection[8];
printf("Enter Name of Player:\n");
fgets(PlayerName, sizeof(PlayerName), stdin);
PlayerName[strcspn(PlayerName, "\n")] = '\0'; // Remove the newline character
printf("Player 1: %s \nPlayer 2: Computer\n", PlayerName);
int Cpoints = 0, Ppoints = 0;
for (int i = 0; i < 3; i++)
{
printf("The Game of Rock, Paper, and Scissors begins:\n Enter your selection:\n");
scanf("%s", Pselection);
num = generateRandomNumber(3);
if (num == 0)
strcpy(Cselection, "rock");
else if (num == 1)
strcpy(Cselection, "paper");
else if (num == 2)
strcpy(Cselection, "scissors");
printf("Compueter: %s\n", *Cselection);
if (strcmp(Cselection, Pselection) == 0)
{
continue;
}
else if (strcmp(Cselection, "rock") == 0 && strcmp(Pselection, "paper") == 0)
Ppoints++;
else if (strcmp(Cselection, "paper") == 0 && strcmp(Pselection, "rock") == 0)
Cpoints++;
else if (strcmp(Cselection, "scissors") == 0 && strcmp(Pselection, "paper") == 0)
Ppoints++;
else if (strcmp(Cselection, "paper") == 0 && strcmp(Pselection, "scissors") == 0)
Cpoints++;
else if (strcmp(Cselection, "scissors") == 0 && strcmp(Pselection, "rock") == 0)
Ppoints++;
else if (strcmp(Cselection, "rock") == 0 && strcmp(Pselection, "scissors") == 0)
Cpoints++;
else
printf("\t*******\tSelection Error! Please check your selection and try again.\t*******\t\n");
printf("score: %d-%d", Ppoints, Cpoints);
}
if (Ppoints >= Cpoints)
printf("The score is %d-%d \nCongratulations! %s is the winner!\n", Ppoints, Cpoints, PlayerName);
else
printf("The score is: %d-%d \nBetter Luck Next Time! The computer won.\n", Ppoints, Cpoints);
return 0;
}
错误信息:
‘__builtin_memcpy’ writing 9 bytes into a region of size 8 overflows the destination [-Wstringop-overflow=]
我尝试打印 Cselection 的一些变体,但输入 Pselection 后输出停止。
strcpy(Cselection, "scissors")
是缓冲区溢出,就像 char Cselection[8];
一样,您写入了 9 个字节(“scissors”的大小 == strlen("scissors") + 1
)。