Usually, if we want to modify a variable in a function, but also change it in its original location outside of the function, we will pass the variable
by reference. That may look like this:
Code (C++)
void print_string(string& val) {
cout << val << endl;
}
However, arrays are a different beast. Yes, you can throw arrays into a function and it will gladly take them. The twist?
They are always automatically passed by reference. There is nothing you can do about this (yet?). But we can take advantage of this to modify values of arrays in functions and have those arrays changed in other places in our code.
Prototype Syntax
Just throw
[]
in after the typename.
Code (C++)
void print_strings(string[]);
Function Declaration
Put the
[]
after the typename
and variable name.
Code (C++)
void print_strings(string lines[]) {
for (int i = 0; i < something; i++) {
cout << lines[i] << endl;
}
}
Notice that that example will not compile. To print out a number of lines from a string array, we also need to know its array size. So therefore:
Code (C++)
//Prototype
void print_strings(string[], int);
//int main()
//Function Declaration
void print_strings(string lines[], int count) {
for (int i = 0; i < count; i++) {
cout << lines[i] << endl;
}
}
Example: Reversing contents in strings of an array size 3
Let's write a program that will take an array of 3 strings and reverse their contents.
No, not "reversing" like what you will do in this lab.... So "Clara Nguyen" will become "neyugN aralC", and etc.
Code (C++)
#include <iostream>
#include <string>
using namespace std;
const int STRING_NUM = 3;
void reverse_strings(string[], int);
int main() {
string lines[STRING_NUM] = {
"Clara Nguyen",
"This is a test line",
"Racecar"
};
reverse_strings(lines, STRING_NUM);
for (int i = 0; i < STRING_NUM; i++) {
cout << lines[i] << endl;
}
}
void reverse_strings(string lines[], int count) {
char temp;
int length, end;
for (int i = 0; i < count; i++) {
length = lines[i].length();
for (int j = 0; j < length / 2; j++) {
temp = lines[i][j];
end = length - j - 1;
lines[i][j ] = lines[i][end];
lines[i][end] = temp;
}
}
}
The output of this program is:
Output
neyugN aralC
enil tset a si sihT
racecaR
Try it out yourself here!
[LINK]