C,指针和void函数

时间:2015-07-03 03:00:26

标签: c++ c pointers char-pointer

找了一个类似的答案,但我尝试的都没有。 有问题,我想通过调用void函数word来更改init()的值,但是当我打印该单词时它不起作用。

花了很多时间在这上面,所以任何帮助都会受到赞赏。

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(&word);
   printf("%s", word);
   displayWord(word, guessedLetters);
   guessLetter(word, guessedLetters);
   return EXIT_SUCCESS;
}

void init(char* word)
{
    int randValue;
    char* randWord;
    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"
    };
    int seed;
    seed = (time(NULL));
    srand(seed);
    randValue = rand() % NUM_WORDS;
    randWord = words[randValue];
    printf("%s", randWord);
    *word = randWord;
}

3 个答案:

答案 0 :(得分:3)

字符串不能在C中分配。

您需要使用strcpy()memcpy()复制字符串

strcpy(word,randWord);

答案 1 :(得分:2)

注意编译器警告。

word.c: At top level:
word.c:16:6: warning: conflicting types for ‘init’
 void init(char* word)
      ^
word.c:8:4: note: previous implicit declaration of ‘init’ was here
    init(&word);

将指针传递给指向init()的指针。

是的,正如@Gopi所说,你不能通过分配来复制字符串。

答案 2 :(得分:1)

以下是解决此问题的两种不同方法:

  1. 传递init(word),然后向下initstrcpy(word, randWord)

  2. word更改为const char *word,继续致电init(&word),将init的定义更改为void init(const char ** word),然后保留作业{{ 1}}。 (在这种情况下,您还应将*word = randWordwords[]声明为randWord。)