I have a function where I want to initialize an int array, do some calculations on it and then return it, but I'm having a hard time figuring out exactly how to do it.
So far I have this (just a test function):
class Test
{
int* func()
{
int x[1];
x[0] = 2;
return x;
}
}
But I get the warning: "Address of local variable 'x' returned". I've been reading up on that and I have an idea why but I can't see how to return the array then. I've been looking through tutorials and books and searched on Google, but I can't find anything about returning arrays from functions.
Another problem I'm having, is with assigning an object to an array. Say for example that I have a class called Tile, and I want an array of Tiles, run through the array and create each new tile with the constructor Tile(int x). That would give me something like this:
#include "Tile.hpp"
class Test
{
void func()
{
Tile tst[1];
tst[0] = Tile(5);
}
}
But then I get the error: "expected unqualified-id at end of input".
I am rather confused as how to create an object in C++. I tried out the previous approach, and looking in a book, it said to use tst[0] (5). Btw, I'm using 2 lines in this case, because in reality I have my "Tile tst[1]" in my header file, and want to create the objects in my cpp file.
Also, studying C++ and trying to fix previous errors, I have found out some things which I would like someone to tell me if I hav e understood them correctly. I am not certain I found the right way to do things.
It is especially pointers and arrays that confuse me. I've read that they are not the same, but I have also found out that I can apparently not use empty arrays as a return for function, or as a parameter, instead I need to use pointers. So not like this:
class Test
{
int[][] func(int[][] x)
{
}
}
but like this instead:
class Test
{
int** func(int** x)
{
}
}
Also, from what I've understood so far, whenever I make a variable with some object type, like Tile t; it automatically creates an object of the Tile class using the default constructor. Therefore, if I have made any constructors, I also need to add the default constructor for it to work. Is that also correct?
Thanks to whomever will help me, in advance.


Sign In
Create Account


Back to top









