dynamic variables

Started by
4 comments, last by ManaStone 21 years, 7 months ago
I am trying to initialize a dynamic variable in a function from a pointer passed down by in main. This is the code i'm using:
  

void main()
{

int *test;

	
testa(test);

cout<<test[1];


delete[] test;

}

 void testa(int *test)
{
	
	test= new int[3];

	test[0]=1;
	test[1]=2;
	test[2]=3;
	

}
  
Why won't this work? How can I get it to work without using global variables? [edited by - manastone on September 2, 2002 12:18:42 AM] [edited by - manastone on September 2, 2002 12:20:48 AM]
-----------------------------Download my real time 3D RPG.
Advertisement
Change the declaration of your testa function to this:
void testa(int* &test)
As you know, you have to use a pointer or reference to allow a function to modify a value in the caller. In this case, the value that you want to modify is itself a pointer. So you need a pointer to a pointer, or a reference to a pointer.


  void testa(int **test){  int *temp = new int[3];  temp[0]=1;  temp[1]=2;  temp[2]=3;  *test = temp;}int main(){  int *test;  testa(&test);  cout << test[1];  delete[] test;  return 0;}  
Same AP again. What Beer Hunter said. Just note that in my way: void testa(int* &t), you pass a reference to the pointer, so you don''t have to dereference in these two lines:
int *temp = new int[3];
-and-
*test = temp;
That was a speedy response, thanks. I thought that if it was a pointer though, you didn’t need to pass by reference.
-----------------------------Download my real time 3D RPG.
Just remember that writing code like this leads to massive memory leaks, since the calling code assumes cleanup responsibility and it isn''t obvious that the function dynamically allocates memory.

This topic is closed to new replies.

Advertisement