我正在用C创建典型的hangman程序,代码编译并运行完美,直到我添加3行代码(25-29),在用户选择了他们想要的游戏模式后将字符串加载到结构中 .
在运行程序时,除非用户在第25-29行中执行“if”语句的选择(标识此语句的注释),否则一切都会起作用,然后终端返回“Abort trap:6”错误 .
经过研究并尝试调试我的代码,我无法找到我写入内存的地方,我还没有初始化 . 代码中的其他所有工作正常,所以我只是寻找有关此错误的具体建议:
char temp2[20]="", phrase[15]="cest la vie";
int guess=0, correct=0, banksize=0, wordsize=0, wordNum=0;
int n, select=0;
time_t t;
strcpy(hangman.guess,temp2);
hangman.incorrect=0;
hangman.wordcount=0;
//This section introduces the user to the game
printf("\nWelcome to Dakota's Amazing Hangman Program!!!(TM)\n");
printf("---------------------------------------------------\n");
printf("I will select a word or phrase at random. \n");
printf("Guess a letter wrong 10 times and you'll hang.\n");
printf("For a word, type and enter 0. For an expression, enter 1:");
scanf("%i",&select);
//This section requests a file and loads it into struct
if(select==0)
{
InputFile();
banksize=LoadWordbank();
srand((unsigned)time(&t));
wordNum=rand() % banksize;
}
if(select==1) //The issue is with the addition of this if statement
{
strcpy(hangman.word[0],phrase);
wordNum=0;
}
wordsize=strlen(hangman.word[wordNum]);
char temp3[wordsize];
for(n=0;n<wordsize;n++)
temp3[n]='_';
strcpy(hangman.progress,temp3);
这是我的结构定义供参考,它是一个全局变量:
struct game
{
char word[30][15];
char progress[8];
char guess[20];
int incorrect;
int wordcount;
};
struct game hangman;
此外,我是这个论坛的新手,所以欢迎任何关于问题格式的有效建议 .
1 回答
在与一些同学合作并确定问题与字符串如何加载到结构中无关之后,我们确定它必须是一个对字长度敏感的变量的问题 .
经过仔细检查后,看起来好像我已经扩展了所有变量的大小,以便在结构中添加一个大于7个字母的单词,除了这个变量:
这导致了代码第33行的问题,我试图将更大的字符串字符串复制到hangman.progress变量中 .
将此扩展到[15]的安全分配后,我不再收到任何错误 . 代码现在看起来如下:
...