Dec 5, 2011 at 9:43pm UTC
I'm having a simple problems. I have the function
void testFunction( int * blabla )
{
blabla = new int[5];
blabla[0] = 1; blabla[1] = 4; blabla[2] = 77;
int ff = blabla[2];
//debug point here
}
which declares a new array
but when i pass the pointer into the function like so
int * yay;
testFunction( yay );
int a = yay[2];
//debug point here
the value a doesn't get the value of 77 as stated in the function. I checked this with the debug points. Any idea of what might be going on?
Dec 5, 2011 at 10:09pm UTC
pointers are y default passed by value. That means the pointer blabla in testFunction is a copy of yay. If you change blabla it will not affect yay.
Dec 5, 2011 at 10:13pm UTC
thanks for the quick reply. Ive also tried variations with references but I get the error that I cant reference a pointer. Its easy when I have something like
void function( int &a )
{
a += 5;
}
but in this case its different and I dont know what to do.
Anyone know how to handle this scenario so I can change the value of yay?
I tried
void testFunction( int & * blabla )
{
blabla = new int[5];
blabla[0] = 1; blabla[1] = 4; blabla[2] = 77;
int ff = blabla[2];
//debug point here
}
but i get an error
Last edited on Dec 5, 2011 at 10:18pm UTC
Dec 5, 2011 at 10:21pm UTC
it seems to work okay when I do it this way
void testFunction( int * & blabla )
{
blabla = new int[5];
blabla[0] = 1; blabla[1] = 4; blabla[2] = 77;
int ff = blabla[2];
}
I don't understand why it works when i reverse the & and the * but it does..
Dec 5, 2011 at 10:31pm UTC
int *&
is a reference to a pointer.
int &*
is a pointer to a reference and is not allowed.
Why not return the pointer from the function instead of passing a parameter?
Last edited on Dec 5, 2011 at 10:31pm UTC