1

I am passing string 2d array to a function in a following way. Is it correct or can it be done better ?

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

void print_name(string name[])
{
    cout<<name[0];
}

int main()
{
    string name[4];
    name[0] = "abc";
    name[1] ="xyz";
    name[2] = "pqr";
    name[3]= "xyq";

    print_name(name);
    return 0;
}
2
  • It is better to think of it as an array of strings and not a 2d array even if a string is an array basically. Commented Jan 25, 2014 at 12:13
  • 1
    I don't see any problem here. Maybe better to use vector<string> name(4) here. Commented Jan 25, 2014 at 12:14

2 Answers 2

2

In C++ a better way is to pass a std::vector as the parameter.

void print_name(const std::vector<std::string>& name)

and

std::vector<std::string> name{"abc", "xyz","pqr","xyq"};

print_name(name);
Sign up to request clarification or add additional context in comments.

11 Comments

const is needed here? You cannot change it even without const, right?
@herohuyongtao missed the reference.
Why not simply void print_name(vector<std::string> name)?
Passing the array is actually simpler (in this case) array[0] is always valid!
@DieterLücking only if you actually pass an array of size at least 1.
|
1

The problem with passing C-style arrays is that the function that you call does not know where it ends. If you must use a fixed-size array, a better approach would be to pass std::array<std::string,4>:

void print_name(std::array<std::string,4>& names) ...

If using std::vector<std::string> is acceptable, it would give your code more flexibility:

void print_name(std::vector<std::string>& names) ...

If none of the above works for you, consider passing the number of array items along with the array, so that your print_name knows how may items it gets:

void print_name(std::string names[], int count) ...

1 Comment

hmm I think, you are correct I should use vector string... Thx a lot for your response.

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.