Sending array from one function to another

Hello all!

I am working on a little project where I have a function that returns a value (integer), like so:

number = my_function(text);

So far so good. But in the function my_function, I also operate on the string (called text) in an array. What I would like to do is return both the integer value into number (which already works), and ”return” the array (both are being ”worked upon” in the function my_function) that is filled with data so I can in turn send said array and number into the next function. (I hope that made sense!).

I am sure this might be considered ”basic”, but I am indeed still new to this and would appreciate help in the matter.

Thanks for reading this,

HMW

PS. I have read about sending an array TO a function. The problem here is returning an array AND an int from a function. DS
You are looking at pointers dude. Basically, I presume that you want 2 elements to be manipulated in a function isn't it?

You could pass your "number" data into a function via a pointer and have it manipulated, and your string "text" too.

http://www.cplusplus.com/doc/tutorial/pointers/
1
2
3
4
5
6
struct number_and_text{
   int number;
   std::string text;
};

number_and_text my_function( std::string str );
Or
std::pair<int, std::string> my_function( std::string str );
Oh dear! Thanks, both of you for your replies. I haven't gotten as far as to pointers yet. I thought I could do this by using ”reference parameters”, but perhaps I am at fault.

Again, thank you for your replies!

/HMW
It is possible to use references for this too. like
1
2
3
4
int my_function( std::string str, std::string& output ){
   output = "Hello World";
   return 0;
}
Hamsterman!

Thanks again for your reply. I spent some time muttering (read: ”swearing”) in front of my screen. And then all of a sudden it worked. I had missed something, namely:

Another unfortunate thing about C++ arrays is that they are always passed by reference


For me, this is not unfortunate at all. Because it means I can use return for the int value, AND manipulate the array which I later use in my second function. The solution looks like:
1
2
3
4
5
6
  number = myfirstfunction (text, freq); // The first function, where ”text” is a string,
   // and ”freq” is the array that is filled with data

  mysecondfunction (number, freq);  // The 2:nd function where the value from the previous
   // function is being used, and the array ”freq” is
   // bring printed. 


The function headers look like:

1
2
myfirstfunction (const string &text, int freq[])
mysecondfunction (int number, int freq[])


Again, thank you for your input. It is highly appreciated.

Best,

HMW

Edit: Forgot to mark as solved. Fixed now!
Last edited on
Topic archived. No new replies allowed.