passing array as reference

Can someone explain to me how is array passed in the function? Also, what is the difference of using between &text[3] and (&text)[3] , which has a parenthesis ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
  using namespace std;

  void show(string (&texts)[3]){

	for(int i = 0; i<sizeof(texts)/sizeof(string); i++){
	cout << texts[i] <<endl;
		}

}

int main() {

	string texts[] = {"one", "two", "three"};

	show(texts);
	return 0;
}
The parentheses are needed to disambiguate the variable from being seen as an array of references, as opposed to passing the array itself by reference. An array (or other container) of references is not possible in C++.

Your code looks correct, if you're questioning its validity.

Though, I suggest using an std::vector -- it keeps its size contained within it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void show(const std::vector<string>& texts){

    for (size_t i = 0; i < texts.size(); i++){
        cout << texts[i] <<endl;
	}
}

int main() {

	vector<string> texts {"one", "two", "three"};
	show(texts);
	
	return 0;
}


The best way to pass a C-style array is as a pointer. Passing it by reference as you do means you can't pass an array of 2 strings or 4 strings, it has to be of length 3. But passing it as a pointer means that the size needs to be passed separately.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

void show(const string *texts, size_t size){
    for (size_t i = 0; i < size; i++)
        cout << texts[i] << '\n';
}

int main() {
	string texts[] = {"one", "two", "three", "four", "five"};
	show(texts, sizeof texts/sizeof *texts);
}

Last edited on
Passing it by reference as you do means you can't pass an array of 2 strings or 4 strings, it has to be of length 3
This is usually the point when such a parameter is used.
Topic archived. No new replies allowed.