【问题标题】:C++ - Error while usign arrays as parameterC++ - 使用数组作为参数时出错
【发布时间】: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];
}

【问题讨论】:

  • 错误似乎很明显。您错误地将sizeofsizeof(words) 一起使用,这会返回指向数组的指针的大小,这不是您想要做的。

标签: c++ arrays string stdstring


【解决方案1】:

sizeof 运算符可能与您想的不完全一样。根据 cppreference:(sizeof) 产生类型对象表示的字节大小。 这可能包括类所需的任何内部成员,而不仅仅是字符串中使用了多少个字符例如。 std::string 有 size()length() 函数,它们是相同的,你可以使用一个向量来代替数组,它也提供了一个 size() 函数。

#include <iostream>
#include <string>
#include <ctime>
#include <vector>

std::string get_random_word(std::vector<std::string>& words)
{
    return words[rand() % words.size()];
}

int main()
{   
    srand(time(0));
    std::vector<std::string> words = {"cpp", "python", "java"};
    std::cout << get_random_word(words);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 2013-06-24
    • 2013-03-10
    相关资源
    最近更新 更多