-2

I was trying to pass myStringArray to a function in the following code.

#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <iostream>

using namespace std;

int loopy(auto someString){
    for (auto Word : someString){
        cout << "In " << __func__ << " word is " << Word << endl;
    }
    return 0;
}

int main(){
    string myStringArray[] = {"abc","def", "xyz", "meh" };
    for (auto Word: myStringArray){
        cout << "In " << __func__ << " word is " << Word << endl;
    }
    loopy(*myStringArray);
    return 0;
}

The o/p I see is:

$ ./a.out 
In main word is abc
In main word is def
In main word is xyz
In main word is meh
In loopy word is a // <<-- this
In loopy word is b // <<--this 
In loopy word is c // <<--this

As you can see, the loopy function only does see the 1st word of the string array(?) that I am passing.

What am I doing wrong, and what's the correct way to pass these C++ nuances to functions? Thanks!

struggling_learner
  • 1,214
  • 15
  • 29

1 Answers1

2

Native array arguments work differently than other containers in C++.

The best way to implement your code using C++ will be to use std::vector:

int loopy(auto &someString){
    for (auto Word : someString){
        std::cout << "In " << __func__ << " word is " << Word << std::endl;
    }
    return 0;
}

int main(){
    std::vector<std::string> myStringArray = {"abc","def", "xyz", "meh" };
    for (auto Word : myStringArray){
        std::cout << "In " << __func__ << " word is " << Word << std::endl;
    }
    loopy(myStringArray);
    return 0;
}

See the minor differences:

  • We use std::vector to keep the strings
  • loopy accepts a reference to the original std::vector
Daniel Trugman
  • 8,186
  • 20
  • 41
  • I wouldn't say these are minor differences :) – 7raiden7 Jun 03 '19 at 06:42
  • @Daniel -Trugman, thank you. I guess half the battle is knowing which container to use. [How](https://stackoverflow.com/questions/56408315/generating-class-datamembers-from-a-vector#comment99414206_56408315) can I know/determine which one to use? – struggling_learner Jun 03 '19 at 06:55
  • @struggling_learner, generally speaking about programming, I would suggest learning one or two courses about data structures. Regarding C++, I would generally use [standard library containers](https://en.cppreference.com/w/cpp/container) – Daniel Trugman Jun 03 '19 at 07:06