How do arrays work in functions?

I'm trying to sort a lot of data in a text file so I'm trying to create a function to make things easier. In my function I'm trying to store values in a string array like this: example[j]="word". In my function I increment j because the function is being called in a loop in main so the next spot in example[] will have to be used. However when I try to print the full array it only prints the last word entered to example[]. When I use the same code in main instead of calling the function the full array prints. What's going on?
PS sorry I didn't post my code its kind of all over the place right now since I'm testing but if you need to see it to help I can post it

the name of an array may as well be a pointer, so passing an array is passing by reference.

I am going to go WAY, WAY out on a limb here and tell you to put the keyword static in front of J and tell me if that helped.

that is, static int j;
...
j++;
etc
Last edited on
that didn't work; I assume you meant to put static in front of j in the function inputs because that's where j is. There is no for loop except for when I'm trying to print the array. I'm using a while loop to read the file data and in that loop I'm calling the function. Like I said when I do it without the function it works but that's pretty cumbersome. Anyways, I'll do some research the array pointer u mentioned, thanks.
If you're using C++ rather than C, the array's type should be std::vector<std::string>, Especially given that you're reading data from a file, how would you know how big the array shoudl be ahead of time?

In my function I'm trying to store values in a string array ... I'm using a while loop to read the file data and in that loop I'm calling the function.

that would look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

void add_to(std::vector<std::string>& v, const std::string s) {
    v.push_back(s);
}
void print(std::vector<std::string>& v) {
    for(const std::string& s: v) std::cout << s << '\n';
}
int main()
{
  std::vector<std::string> v;
  std::string s;
  std::ifstream f("test.txt");
  while(f >> s) add_to(v, s);
  print(v);
}

live demo: http://coliru.stacked-crooked.com/a/b677a3318aab183b

(of course if you already know all about vectors and strings and are getting into advanced topics such as arrays it's another story)
Last edited on
we probably need to see the function body.
Topic archived. No new replies allowed.