Archived

This topic is now archived and is closed to further replies.

ManaStone

dynamic variables

Recommended Posts

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]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Change the declaration of your testa function to this:
void testa(int* &test)

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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;

Share this post


Link to post
Share on other sites