how to pass one element of an array only

Hello everybody,

I know how to pass a complete multidimension array to a function, but how can I pass one element only of a multifunction array to a function? how will the actual parameter list and former parameter list look like?

Thank you.
The function doesn't care that the argument is part of an array. Just write the function to accept an argument of whatever type the elements are.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

void print(int value)
{
	std::cout << value << "\n";
}

int main()
{
	int arr[] = {2, 5, 9};
	
	print(arr[1]); // passes an element of the array `arr` as argument to the function `print`
}
Last edited on
If you actually want to change that element of the array then make the dummy argument a reference.

But, otherwise, as Peter87 says, it is (nearly) irrelevant that the argument is one element of an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

void a_function( int &x )
{
   x += 100;
}


int main()
{
   int A[][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   cout << "Before:\n";
   for ( int i = 0; i < 3; i++ )
   {
      for ( int j = 0; j < 3; j++ ) cout << A[i][j] << '\t';
      cout << '\n';
   }

   a_function( A[1][1] );

   cout << "\nAfter:\n";
   for ( int i = 0; i < 3; i++ )
   {
      for ( int j = 0; j < 3; j++ ) cout << A[i][j] << '\t';
      cout << '\n';
   }
}


Before:
1	2	3	
4	5	6	
7	8	9	

After:
1	2	3	
4	105	6	
7	8	9	




I say "nearly" because you could put the line
*(&x-1) += 100;
in a_function with predictable, if daft, results.
Last edited on
Thanks a lot, but, how about multidimensional array?
You need to provide as many indexes as dimensions. If you have 10 dimension you need to provide 10 indexes.

Or are you trying to do something else with that array?
@allenmaki, you have been given code for 2-d arrays (not that the function call is essentially any different from a 1-d array).

What exactly is it that you want to do?

Please supply a (small) code example.
Topic archived. No new replies allowed.