我正在做一个词汇培训项目,在那里你可以添加、练习、查看和改变你的词汇.对于英语中的每个单词(最多50个字符),我希望有一个瑞典翻译/定义(最多999个字符)和几个例句(最多10个,每个包含最多999个字符).为此,我使用了一个名为Word的 struct ,由于我需要多个单词,因此我创建了一个大小为100(最多100个单词)的文字array.这种方法运行得很好,直到我创建了一个函数,希望在其中声明一个新的WORD类型的临时数组(因为我将随机化顺序,并且我不希望第一个数组受到影响).我将大小设置为MaxSize(100),但随后整个程序终止.经过一些实验后,我发现当我将临时数组的大小设置为92时,程序可以工作,但如果我将其设置为93时,程序就不能工作.这是为什么?这是否与我的数组占用了太多内存有关?我对c编程非常陌生,因此一个简单的解释将是很棒的.代码如下:谢谢.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXWORDS 92
#define MAXEWORD 50
#define MAXSENTENCE 999
#define MAXNR 10
typedef struct {
char eWord[MAXEWORD];
char sWord[MAXSENTENCE];
char sentence[MAXNR][MAXSENTENCE];
} Word;
void printEnglishWords(Word theWords[], int thePos) {
for(int i=0; i<thePos; i++) {
printf("%s, ", theWords[i].eWord);
}
}
void shuffleWords(Word theWords[], int thePos) {
Word wordTemplate[MAXWORDS];
Word hold;
for(int i=0; i<thePos; i++) {
wordTemplate[i]=theWords[i];
}
for(int i=0; i<thePos; i++) {
int index=rand()%thePos;
hold=wordTemplate[i];
wordTemplate[i]=wordTemplate[index];
wordTemplate[index]=hold;
}
printf("\n");
printEnglishWords(wordTemplate, thePos);
}
int main(void) {
srand((unsigned) time(NULL));
Word myWords[MAXWORDS];
int pos;
myWords[0]=(Word){"Dog", "Hund", {"I own a dog"}};
myWords[1]=(Word){"Cat", "Katt", {"I do not own a cat"}};
myWords[2]=(Word){"Food", "Mat", {"I am hungry and I need some food"}};
pos=3;
printEnglishWords(myWords, pos); //output is Dog, Cat, Food,
shuffleWords(myWords, pos); //output is Food, Dog, Cat,
return 0;
}
当MAXWORDS为92时,输出写在上面.但是,当MAXWORDS为93时,只会写入"Dog,Cat,Food",并且shffleWords函数不起作用.