【发布时间】:2021-11-28 21:23:14
【问题描述】:
我创建了一个单词数组并创建了一个函数来从数组中返回一个随机单词。但它显示了这个错误 -
hangman.cpp: In function 'std::__cxx11::string get_random_word(std::__cxx11::string*)':
hangman.cpp:17:33: warning: 'sizeof' on array function parameter 'words' will return size of 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' [-Wsizeof-array-argument]
size_t length = sizeof(words) / sizeof(words[0]);
^
hangman.cpp:15:47: note: declared here
std::string get_random_word(std::string words[])
^
这里是代码-
#include <iostream>
#include <string>
#include <ctime>
std::string get_random_word(std::string words[]);
int main()
{
srand(time(0));
std::string words[] = {"cpp", "python", "java"};
std::cout << get_random_word(words);
return 0;
}
std::string get_random_word(std::string words[])
{
size_t length = sizeof(words) / sizeof(words[0]);
return words[rand() % length];
}
【问题讨论】:
-
错误似乎很明显。您错误地将
sizeof与sizeof(words)一起使用,这会返回指向数组的指针的大小,这不是您想要做的。
标签: c++ arrays string stdstring