I'm sort of new to C++ and programming in general. I'm making a pokemon remake of the old gameboy version for fun, and I'm having trouble passing a whole structure as an arguement.
This is a shortened version to highlight the problem I'm having:
struct Enemy_Pokeman
{
string opp_name;
int num_pokeman;
int pokeman_LVL;
};
void pl_Pokeman(Enemy_Pokeman);
void pokeman_data(string opp_name, int num_pokeman, int pokeman_ID[], int pokeman_LVL[],
int purpose)
{
Enemy_Pokeman enemypokeman[num_pokeman];
enemypokeman[0].opp_name = opp_name;
enemypokeman[0].num_pokeman = num_pokeman;
for(int i=0; i<num_pokeman; i++)
enemypokeman[i].pokeman_LVL = pokeman_LVL[i];
pl_Pokeman(enemypokeman); //Function call - Codeblocks detects error
//on this line
}
void pl_Pokeman(Enemy_Pokeman enemy)
{
cout << endl;
}
Sorry if this doesn't make sense, I didn't want to post the entire thing, so I chopped it up a bit.
The problem is that it won't accept Enemy_Pokeman as an arguement.
Function pl_Pokeman only takes Enemy_Pokeman type while you passed in an array of Enemy_Pokeman
You update pl_Pokeman function to take array as input:
void pl_Pokeman(Enemy_Pokeman enemy[], int arraySize);
Or
template<typename T, size_t N>
void pl_Pokeman(Enemy_Pokeman (&enemy)[N])
you're passing to your function whole array of Enemy_Pokemans, not just one element. function expects one element only. also, you're creating that array within a function, so it's a local variable. if function pokemon_data returns, that array will be destroyed.
For Single structure-
When you are passing the structure as a argument, you should pass with & operator.
pl_Pokeman(&enemypokeman); // Fix 1
While catching it you need to catch it with Structure pointer.
void pl_Pokeman(Enemy_Pokeman *); // Fix 2
For Array of structure-
pl_Pokeman(&enemypokeman,size); // pass it with size
while catching it
void pl_Pokeman(Enemy_Pokeman (*)[], int );
Related
I have written a function that takes in a dynamic length array but with fixed inner array size, the second parameter in the function is the length of the parent array. When I try to access the nested values however, I get the issue mentioned above.
void myFunc(int arrOfArr, int arrOfArrLen) {
// try to access
arrOfArr[0][1]; // expect val2
}
example usage
myFunc(
{
{val1, val2},
{val3, val4}
},
2
);
edit: I realize "contextually" obviously an integer has no indexes, but that's how you declare an array it seems...(truthfully in Arduino context) but apparently it's still C++
Here's a runable demo of above from the first sandbox Google returned
http://cpp.sh/5sp3o
update
I did find a solution, it's ugly but it works:
instead of passing in a "raw" nested array as a param, I set it as a variable first eg:
int arrOfArr[][3] = {
{val1, val2},
{val3, val4}
}
Then in the function I do the same thing
void myFunc(int arrOfArr[][3], int arrOfLen) {
// access
}
Call it
myFunc(arrOfArr, 2);
As I said it's ugly but works for me, this is a passing project thing not a low-level dev, maybe will learn it fully later on but not needed in day job.
edit: apparently the thing I was trying to do initially eg. embed an initializer list as a param does not work.
if you want to pass a nested array, the declaration may be:
template<size_t N>
void myFunc(int const arrOfArr[][N], int arrOfArrLen) {
// ...
}
and you can remove the template argument if N is already decided.
const size_t N = 3;
void myFunc(int const arrOfArr[][N], int arrOfArrLen) {
// ...
}
but it doesn't work if you pass a brace-enclosed initializer, you can add a overloaded function:
template<size_t M, size_t N>
void myFunc(int const (&arrOfArr)[M][N], int arrOfArrLen){
// attention: int *const*
// ...
}
I need to pass array of structures to a function and I make it this way:
it's my function
void ShowRoutes(Route *routeList, int n, string title) { //... }
and it's function call
ShowRoutes(routeList, n, "Unsorted list: ");
but I would like to know are there other ways to pass array of structures to function?
Two ways I know of to pass arrays to functions.
The way you have it:
void ShowRoutes(Route *routeList, int n, string title) { //... }
or
void ShowRoutes(Route routeList[], int n, string title) { //... }
Either way you write the function, you would still call it the same way:
ShowRoutes(routeList, n, "Unsorted list: ");
But as others mentioned, would be a good idea to learn std::array and std::vector.
I am trying to pass a structure I created in a function to another function so basically what im trying to do is dynamically create the amount of structures needed the amount of structures is in a text file so in the text file there would be a number like 5 and and 5 data sets. I want to pass the structures I created in my function to another function. I started programming a few months ago so forgive me if there is a simple solution or if this question has been asked.
struct graph
{
int Max,Min,index;
double dataArray[300];
};
void readfile()
{
int amount;
char tmpSTR,nmbrGraph;
ifstream myFile("data1.txt",ios::in);
myFile>>amount;
myFile>>tmpSTR;
myFile>>nmbrGraph;
graph* Data = new graph[amount];
for(int j=0;j<nmbrGraph;j++)
{
for(int i=0;i<299;i++)
myFile>>Data[j].dataArray[i];
}
//hOW WOULD I PASS THE STRUCTURE "DATA" TO THE FUNCTION anotherFunction?
}
void anotherFunction()
{
for(int i = 0;i<300;i++)
cout<<Data[scroll].dataArray[i])<<endl; /*Error here! scroll being an
integer declared globally*/
}
Pass the graph* pointer by value or reference to anotherFunction as an argument. Also, it is important to include the number items, as that was determined by reading the file and not knowable beforehand.
// by value
void anotherFunction(graph* Data, int amount);
// by reference
void anotherFunction(graph*& Data, int amount);
So I have a struct as follows:
struct threadData{
string filename
int one;
int two;
};
and I created an array of these structs like this:
pthread_t threadID[5];
struct threadData *threadP;
threadP = new struct threadData[5];
then I'm passing this array of structs to a thread function as follows:
for(int i = 0; i < 5; i++){
pthread_create(&threadID[i], NULL, threadFunction, (void * ) threadP[i]);
}
and this is how my threadFunction is written:
void *threadFunction(void * threadP[]){
}
I've tried various things, but I always get the error that what I pass in is not correct, how do I do this properly so that I can access and process the variables in each struct object I pass in? I have a feeling that my syntax somewhere is wrong due to me using an array of structs...I just don't know where or what exactly is wrong. Any help would be appreciated!
void *threadFunction(void * threadP[]){
Functions cannot have parameters of array types in C++, instead the parameter has to be a pointer, and an array used as a function argument decays to a pointer to the first element, so that declaration is equivalent to:
void *threadFunction(void ** threadP){
Which clearly isn't the right type to pass to pthread_create
You need to pass a function with this signature:
void *threadFunction(void * threadP)
So I'm still rather new to programming/C++, and still trying to wrap my head around pointers and passing by reference and everything. A program I'm trying to figure out now needs to pass an array of structs to another function. I've gotten it working by just passing the array directly there. It seems to work fine. However, what I'm concerned about is that I believe I'm passing it by value, and I understand that it's better to pass structs by reference, so you're not making a copy of the struct every time...
Anyway, here's a basic example of what I'm doing:
struct GoldenHelmet {
int foo;
string bar;
};
void pass (GoldenHelmet ofMambrino[], int size);
int main () {
GoldenHelmet ofMambrino[10];
int size = sizeof(ofMambrino) / sizeof(ofMambrino[0]);
ofMambrino[1].foo = 1;
pass(ofMambrino, size);
cout << ofMambrino[2].foo << endl;
return 0;
}
void pass (GoldenHelmet ofMambrino[], int size) {
ofMambrino[2].foo = 100;
ofMambrino[2].bar = "Blargh";
}
From what I understand, it works because arrays are already pointers, right? But the way I have that configured, am I still passing a copy of the struct and everything to the pass() function? I've tried to pass it by reference, but it doesn't seem to want to work any way I've tried.
The C++ way:
#include <array>
typedef std::array<GoldenHelmet, 10> Helmets;
void pass(Helmets &);
int main()
{
Helmets h;
h[1].foo = 1;
pass(h);
//...
}
void pass(Helmets & h)
{
h[2].foo = 100;
// ...
}
Indeed, we pass the array by reference.
This syntax:
void pass (GoldenHelmet ofMambrino[], int size)
is actually quite confusing. Because you are not passing an array, you are passing a pointer. They are not the same thing though, don't get confused. This oddity only applies to function parameters. The above is exactly identical to this:
void pass (GoldenHelmet * ofMambrino, int size)
It's actually impossible to pass an array by value, unless it is a sub-object of another object. You can pass them by reference, you need to include the size though, but you can do that using a template:
template<int N>
void pass (GoldenHelmet (&ofMambrino)[N])
These are all possible, but none of them are pass by value. Just think of ofMambrino as being the address of the beginning of the array, and that is what you are passing.
void pass (GoldenHelmet ofMambrino[], int size)
void pass (GoldenHelmet ofMambrino[10], int size)
void pass (GoldenHelmet *ofMambrino, int size)
void pass (GoldenHelmet (&ofMambrino)[10], int size)
Arrays are represented and passed as pointers, so you are not copying anything here. In contrast, if you were passing a single struct, it would be passed by value.
Below is a code snippet to illustrate this last point:
void passByVal (GoldenHelmet ofMambrino) {
ofMambrino.foo = 100;
ofMambrino.bar = "Blargh";
}
void passByRef (GoldenHelmet& ofMambrino) {
ofMambrino.foo = 100;
ofMambrino.bar = "Blargh";
}
int main() {
GoldenHelmet h;
passByVal(h); // h does not change
passByRef(h); // fields of h get assigned in the call
}
First of all array is not pointers. We refer this as a pointer in the argument list because when we use
int x[ ]
x is actually const pointer that points the beginning of the array. And when you pass this to a function you send the adress of the memory that is beginning of the array. Thats why when you make a change in your function, you make change in the adress of your variable in the caller section actually. This is actualy simulated call by reference not call by reference. But effect is same with call by reference because you are working on memory locations. For this reason when you send array of your struct you pass actually adress of your array of structs. Thats why when you change value on this, you actually change your structs.
To use call by reference, one thing you must to do is to define your function prototype like
void f(int ¶m)
and when calling function, it is same with the others.
To summarize:
int main()
{
int x;
// simulated call by reference that use adress of variable,
// lets say adress of x is 19ff
f(&x); // actually you send 19ff
f(x); // call by reference that use reference of variable
}
// simulated call by reference
void f(const int *y)
{
// when you use like *y=10, you are writing on memory area 19ff, you actually
// change memory area that is belong to x in the main
}
// call by reference
void f(const int &y)
{
}