I've googled this and found loads of threads, but none seem to help me.
I am doing a project which requires me to use a function that uses an array from the main code. The output is then a different array.
This is a simple code which i found through google:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int* test(int a,int b)
{
int* pointer;
int info[2];
pointer=info;
info[0]=a;
info[1]=b;
return pointer;
}
int main()
{
int* ptr=test(200,100);
cout << ptr[1] << endl;
return 0;
}
I have learned that you require a pointer to call an array from a function. The above code works, but not for my purposes.
My array contains class data with 4 arguments. My class is called particle. I have replaced the int with particle as shown below. The code runs; however, the information in the called array is always -9.25596e+061.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
particle* test(int a, int b)
{
particle* pointer;
particle info[2];
pointer = info;
info[0] = particle(a,a,a,a);
info[1]= particle(b,b,b,b);
return pointer;
}
int main()
{
particle* ptr=test(200, 100);
ptr[0].print();
ptr[1].print();
return 0;
}
This doesn't work because you assign the address of a local array to your pointer. As you probably know, local objects are destroyed when the code leaves their scope. What you want to do is, replace
1 2
particle* pointer;
particle info[2];
with
particle* pointer = new particle[2];
The above code you posted should, by no means, work. If that code makes it through without letting your program explode that's just dumb luck rather than proof of concept.
PS: This leaves you with the responsibility of destroying the array with delete whatever_the_name_of_your_array_was[] if you don't need it anymore. If you don't do that, you'll cause memory leaks.
int* test(int a,int b)
{
int* pointer;
int info[2];
pointer=info;
info[0]=a;
info[1]=b;
return pointer;
}
is not right. This code creates a local variable and returns a pointer to it. However after a function is finished, any memory used for it's local variables may (and will) be reused.
The best solution here would be an std::vector.