So this is a project that I've been doing for myself for fun, but have ran into a small problem. I defined a structure in a header file, and declared an array in the main function, initializing it to 0. However, I'm having trouble with passing it by reference, since I want to pass it to the function, change whatever's in the array, and return it.
it cant be named struct becouse it's a reserved word. Try nameing it, say, -"structure" or "struct1", or "mystruct", anything but "struct"! And, you can't initialise it just like that. You must declare a constructor and the call it in the initialiser list!
Arrays are passed by reference normally, because they really are just pointers when broken down. Passing an array through a function always uses reference
@viliml Oops, I was kinda doing the pseudocode fast and wasn't really thinking lol. But doing that way works in my program and compiles with no error at all. And it works the way it should. The structure is already declared within the namespace, and usingnamespace SOMETHING enables me to use it. And then I initialized all elements within the array to 0 (I print out all the elements, and without initializing it to 0, it displays lots.... and lots of garbage). I just need to figure out how to pass it to myFunction(). So it is right and there are no compilation errors. Unless you're talking about something else that's COMPLETELY different.
@Need4Sleep How do you pass an array by reference?
you pass by reference in this way SOMETHING::Structure& struct1
or in general value_type& variable value_type can be any type, int, float, vector, yourownclass
1 2 3 4 5
void myFunction(SOMETHING::Structure& struct1 )
{
//Change elements of struct1
}
you call the function like
1 2 3 4 5
//somewhere in your main
Structure struct1[MAX] = {0};
myFunction(struct1);
//here the new value of struct1 can be access
Right, but it's also an array, and what I want myFunction to do is edit the elements within struct1. But I can't edit the elements if I can't even print out the information of each individual element in myFunction
What is the point of your namespace if you just usenamespace something? Namespaces help organize, like namespace GameFunctions hold functions related to testing if the game runs GameFunctions::PlayerOneDead() ,while a namespace Messages displays informations on the game Messages::DisplayStats(PlayerOne).
Arrays are passed with reference BY DEFAULT, no need to add a reference operator in there. I stated this earlier in my other post
#include <iostream>
#include "SOMETHING.h"
constint MAX = 5;
//Prototype
void myFunction();
int main()
{
usingnamespace std;
usingnamespace SOMETHING;
Structure ArrayOfStructs[MAX] = {0};
myFunction(ArrayOfStructs); //Arrays are passed by reference without the need of a '&'
//...
return 0;
}
void myFunction(Structure Array[]) //Parameter for array of structures
{
//Change struct array elements
//Return changed struct array
}