I want to pass a pointer to an array to a newly instantiated class. This new class will determine how big the array needs to be, allocates it with "new" and fills it. Then the original class needs to know where that array is located.
I think I need to pass a pointer to the pointer, but I do not know how to do this properly.
-Tony
Passing a pointer to a pointer? Topic is solved
Something like (disclaimer: untested, used only to give an idea) :
Code: Select all
void foo()
{
int* myarray;
bar( &myarray );
}
void bar(int** array_ptr)
{
*array_ptr = new int[128];
}
"Keyboard not detected. Press F1 to continue"
-- Windows
-- Windows
Auria,Auria wrote:void bar(int** array_ptr)
{
*array_ptr = new int[128];
}
Thanks. I just did it that way and it works! What I had hoped to be able to do was use a more simple name for that double-indirection. I wanted to be able to refer to the pointer "*array_ptr" as something like "array".
It is harder and less intuitive to write
Code: Select all
*array_ptr[1] = 23;
Code: Select all
array[1] = 23;
You could simply do something like :
(again, same disclaimer, untested)
Or again :
Code: Select all
void foo()
{
int[] myarray;
bar( myarray );
}
void bar(int[]& array_ref)
{
array_ref = new int[128];
array_ref[0] = 123;
array_ref[1] = 345;
// etc...
}
Or again :
Code: Select all
void foo()
{
int* myarray = bar();
}
int* bar()
{
int* array_ptr = new int[128];
array_ptr[0] = 123;
array_ptr[1] = 345;
return array_ptr;
}
"Keyboard not detected. Press F1 to continue"
-- Windows
-- Windows
Auria,Auria wrote:You could simply do something like :
Code: Select all
void foo() { int[] myarray; bar( myarray ); } void bar(int[]& array_ref) { array_ref = new int[128]; array_ref[0] = 123; array_ref[1] = 345; // etc... }
THAT is what I was looking for! I had come to the conclusion by checking around that I needed to use the ampersand in the args of the constructor, but I was not sure how to go about doing it.
I was surprised by the brackets in the arg. I had been thinking that maybe I needed to code it something like this.
Code: Select all
void foo()
{
int *myarray;
bar( &myarray );
}
void bar(int* &array_ref)
{
array_ref = new int[128];
array_ref[0] = 123;
array_ref[1] = 345;
// etc...
}
I have never seen a definition written as "int[] varname" (I am familiar with int *varname), but my experience in C++ is fairly limited, especially with more advanced pointer and reference topics.
-Tony