Skip to main content
gamedev.net
🔒 Locked

passing arrays by pointer problem

Started by papa 1 reply 200+ views
Original Post
papa
papa
hi Could somebody tell me why I cant return the correct modified array contents.
void changeArray( char *arr )
{
        // resize array

	char* tmp = new char[10];
	memset(tmp,0,10);
	memcpy(tmp, arr, 4); // copy old contents 'STAR'

	delete [] arr;
	arr = tmp;
}

main()
{
char *a = new char[4];
memset(a,0,4);
a[0] = 'S'; a[1] = 'T'; a[2] = 'A'; a[3] = 'R'; 
change( a ); 
// should be 'S' using a[0] but it prints out some junk

}
When printing out from a[] I cant see the old contents that I copied into tmp and tehn put itback into a[]. Why? Should I pass the array like this change( &a); but then this is like double pointer am I right. How should I delete it if its correct so there are no mem leaks. When I try this it causes errors.
  
void changeArray( char **arr )
{
        // resize array

	char* tmp = new char[10];
	memset(tmp,0,10);
	memcpy(tmp, *arr, 4); // copy old contents 'STAR'

	for( int i=0; i<4; ++i)
		delete [i] arr;
	*arr = tmp;
}
Sorry I just started programming. [edited by - papa on May 5, 2004 12:49:13 PM]
nmi
nmi

The problem arises when doing ''arr = tmp;'', which will modify the pointer that was passed to the function changeArray() on the stack. However, this pointer is just a copy of the original one in function main(). You can modify the original one if you declare arr as char**, or much simpler as char*&. See the code for an example of the latter one:


void changeArray( char*& arr ){
// resize array

char* tmp = new char[10];
memset(tmp,0,10);
memcpy(tmp, arr, 4);
// copy old contents ''STAR''

delete [] arr;
arr = tmp;
}



papa
papa
Silly me. I discovered the problem I think.

I should not use for loop just delete [] *arr; I guess... Am I right? and there should be an asterisk in front of the 'arr' ie.
delete [] *arr whereas before I had delete [] arr without teh asterisk which was wrong. Wasnt it?

Is the code correct below? Is it the right way to delete the entire array or not? please let me know



void changeArray( char **arr )
{
// resize array char* tmp = new char[10];

memset(tmp,0,10);
memcpy(tmp, *arr, 4); // copy old contents 'STAR'

delete [] *arr;
*arr = tmp;}
}





[edited by - papa on May 5, 2004 1:51:14 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.