C++ - Error while usign arrays as parameter

Viewed 51

I made a array of words and made a function to return a random word from the array. But it shows this error -

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[])
                                               ^

Here is the code -

#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];
}
1 Answers

The sizeof operator may not be doing exactly what you think. According to cppreference: (sizeof) Yields the size in bytes of the object representation of type. This may include any internal members needed for the class, and not just how many characters are used in the string for example. std::string has the size() and length() functions for this, which are the same, and instead of using an array you can use a vector that also provides a size() function.

#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;
}
Related