c++arraysstringfunction

Error When Passing String array to function in C++


Hi guys I've some errors when passing some strings of array in C++, do you know what's wrong with this code guys?, Thankyou

#include <iostream>
#include <string>

void showData(string data[]);

int main()
{

    string namaMahasiswa[] = {"Nico", "Yonathan", "Andre", "Ratu"};

    enum option{ SHOW = 5 };

    switch (5)
    {
    case SHOW:
        showData(namaMahasiswa);
        break;
    }
}

void showData(string data[])
{
    for (int z = 0; z < sizeof(data) / sizeof(*data); z++)
    {
        cout << data[z] << endl;
    }
}

This is the error :

'int main()':
index.cpp:61:18: error: could not convert '(std::string*)(& namaMahasiswa)' from 'std::string*' {aka 'std::__cxx11::basic_string<char>*'} to 'std::string' {aka 'std::__cxx11::basic_string<char>'}
   61 |         showData(namaMahasiswa);
      |                  ^~~~~~~~~~~~~
      |                  |
      |                  std::string* {aka std::__cxx11::basic_string<char>*}

In function 'void showData(std::string*)':
index.cpp:83:36: warning: 'sizeof' on array function parameter 'data' will return size of 'std::string*' {aka 'std::__cxx11::basic_string<char>*'} [-Wsizeof-array-argument]
   83 |     for (int z = 0; z < sizeof(data) / sizeof(*data); z++)

index.cpp:80:22: note: declared here
   80 | void showData(string data[])

So it means we can't pass string array to a function like that or maybe I've to use some char?


Solution

  • As an alternative to the answer provided by @ACB, you can use a std::array.

    #include <array>
    #include <string>
    #include <iostream>
    
    template <std::size_t S>
    void foo(std::array<std::string, S> &bar) {
        for (auto &i : bar) {
            std::cout << i << '\n';
        }
    }
    
    int main() {
        std::array<std::string, 3> baz = {"hello", "world", "wooble"};
    
        foo(baz);
    
        return 0;
    }
    

    We could even use the template to allow for std::arrays of other types. As long as there is an applicable << overload with std::ostream and T.

    #include <array>
    #include <string>
    #include <iostream>
    
    template <typename T, std::size_t S>
    void foo(std::array<T, S> &bar) {
        for (auto &i : bar) {
            std::cout << i << '\n';
        }
    }
    
    int main() {
        std::array<std::string, 3> baz = {"hello", "world", "wooble"};
    
        foo(baz);
    
        return 0;
    }