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

  • You have to pass it in as

    void showData(string* data, size_t len);
    

    but since you are using c++ its better to use something like vector instead of C arrays. A different approach would be to use a template to deduce the size like this:

    template<size_t S>
    void showData(string (&data)[S]);
    

    this gives you the size of the array as S