在我的main方法中调用方法时遇到一些麻烦。我只是想从" init"中的数组中随机获取一个单词。方法,找到它的长度,然后打印所有信息。 (随机数生成,哪个词也相关,它的长度)。刚开始使用C,所有帮助都表示赞赏。
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "hangman.h"
void init(char* word);
int main(void)
{
char word[MAX_WORD_LEN + 1];
unsigned wrongGuesses = 0;
int guessedLetters[ALPHABET_SIZE] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
init();
return EXIT_SUCCESS;
}
void init(char* word)
{
const char* words[NUM_WORDS] = {
"array", "auto", "break", "case", "cast",
"character", "comment", "compiler", "constant", "continue",
"default", "double", "dynamic", "else", "enum",
"expression", "extern", "file", "float", "function",
"goto", "heap", "identifier", "library", "linker",
"long", "macro", "operand", "operator", "pointer",
"prototype", "recursion", "register", "return", "short",
"signed", "sizeof", "stack", "statement", "static",
"string", "struct", "switch", "typedef", "union",
"unsigned", "variable", "void", "volatile", "while"
};
srand(time(NULL));
int randomNumber;
randomNumber = rand() %51;
printf("%d\n", randomNumber);
int wordLength = strlen(words[randomNumber]);
printf("%d %s\n", wordLength, words[randomNumber]);
}
答案 0 :(得分:1)
您已将init
声明为参数char*
的函数,但在没有参数的情况下调用它。
答案 1 :(得分:0)
修改函数原型以及从void init(char * word)
到void init()
的定义,因为你已经在函数中定义了const char* words[NUM_WORDS]
,你不需要传递任何参数。
答案 2 :(得分:0)
不要为您的功能命名' init'如果它不是为初始化任何东西而设计的。将其命名为getRandomWord
,或者说是什么。
您的words
数组包含50个项目,因此其有效索引的范围为0到49.因此,您应截断rand()
结果模50,而不是51.无论如何,它更安全使用预定义的宏来表示常量:
int randomNumber = rand() % NUM_WORDS;
<强> ADDED 强>
您也可以删除大小并让编译器在需要时进行计算。然后,您可以在未来版本中自由添加新单词而无需更新NUM_WORDS
定义:这是技巧:获取数组的大小(以字节为单位)并将其除以数组项的大小。
const char* words[] = { // size defined implicitly by a words list
"array", "auto", "break", "case", "cast"
// .....
};
int num_words = sizeof words / sizeof words[0];
int randomNumber = rand() % num_words;
(&#39;已添加&#39;。)
多次使用srand()
,rand()
次:
main()
{
char word[ MAX_WORD_LEN + 1];
// some preparations
.....
srand( time(NULL) );
// main work
while( still_want_to_work )
{
getRandomWord( word );
processTheWord( word ); // eg. print it
}
}
然后getRandomWord(char *word)
可能会向调用者发送一个随机字词:
void getRandomWord(char* word)
{
const char* words[] = {
"array", "auto", "break", "case", "cast"
//......
};
int randomNumber = rand() % (sizeof words / sizeof words[0]);
printf("%d\n", randomNumber);
int wordLength = strlen(words[randomNumber]);
printf("%d %s\n", wordLength, words[randomNumber]);
// copy the word to a buffer prepared by a caller
strncpy( word, words[randomNumber], MAX_WORD_LEN );
// and terminate the result in case the source is too long
word[MAX_WORD_LEN] = 0;
}