Passing an Array of Structs to a Function

Can someone point me in the right direction? I'm a beginner but i'll try to explain this the as best as I can. How can I edit specific fields from my struct in different elements of an array through a function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
typedef struct 
{
	int x;
	int y;
	int z;

}thing;

thing arr[10];

SomeFunction(&arr);

void SomeFunction(thing *obj)
{
	obj[0].x = 100; //Change the x value in the first element of my array?
	obj[1].x = 200;
	obj[2].x = 300;
}
Arrays are by default passed through as a reference instead of a copy. So by passing through the array you can modify it.

e.g
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>
#include <string>

using namespace std;

struct MyStruct {
	string name_;
};

void F(MyStruct array[], unsigned length) {
	for (unsigned i = 0; i < length; ++i)
		array[i].name_ += " YAY";
}

int main() {

	MyStruct array[2];

	array[0].name_ = "element 1 : ";
	array[1].name_ = "element 2 : ";

	F(array, 2);

	for (unsigned i = 0; i < 2; ++i)
		cout << array[i].name_ << endl;

	return 0;
}
Topic archived. No new replies allowed.