0

I am trying to create a function that prints the elements of an array. I set it up so it calculates the size of the array, but I cannot figure why it doesn't work. Can you give me some suggestions? Thanks!

#include <iostream>
#include <string>
using namespace std;

void print_array(string s){
    for(int i = 0; i < ( sizeof(s) / sizeof(s[0]) ); i++){
        cout << s[i] << "\n";
    }
}

int main()
{
    string names[5] = {"Dante", "Greg", "Bob", "Victor", "Saber"};
    print_array(names);
}

5
  • 3
    You're passing in (and expecting) a string, not an array of strings. Commented Jan 15, 2020 at 21:44
  • 2
    Tip: Use std::vector as a default for array-type things. This container includes length information and works well with for(auto x : vec) type iteration. Commented Jan 15, 2020 at 21:46
  • How can I modify it to work? I am a beginner to C++. Commented Jan 15, 2020 at 21:47
  • ` void print_array(vector<string> s){ for(int i = 0; i < s.size(); i++){ cout << s[i] << "\n"; } }` Commented Jan 15, 2020 at 21:50
  • 1
    Read the compiler's error messages Commented Jan 15, 2020 at 22:16

2 Answers 2

1

Welcome to Stack Overflow! Be aware that there are many questions similar to this that have received answers.

As mentioned in a comment, you would need to specify the size of the array if you plan on passing it into a function, because the compiler will look at it not as an array of strings (string s[]), but as a pointer to strings (string s*). Thus, you would need to modify it a little like so:

#include <iostream>
#include <string>
using namespace std;

void print_array(string s[], int size){
    for(int i = 0; i < size; i++)
    {
        cout << s[i] << "\n";
    }
}

int main()
{
    string names[5] = {"Dante", "Greg", "Bob", "Victor", "Saber"};
    print_array(names, sizeof(names) / sizeof(names[0]));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. Simple and to the point. So, the solution is to calculate the size of the array before passing it to the function.
1

You are passing a string instead of an array of strings. You could modify your code by using vectors like this:

void print_array(const std::vector<std::string> &vector){
    for (const auto &string : vector) {
        std::cout << string << "\n";
    }
}

int main()
{
    std::vector<std::string> names = {"Dante", "Greg", "Bob", "Victor", "Saber"};
    print_array(names);
}

Using vectors allows you to use auto generated for loops, wich are easy to read and use.

1 Comment

Thanks! I didn't study about vectors yet, they seem to make things much easier for us!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.