Pointers, methods and new

Started by
3 comments, last by Koobazaur 19 years, 10 months ago
I have a small problem I can''t resolve... I have a method to which I pass a pointer to an array of variables, the method is supposed to modify each of the variable in the array. When I use new type[something] before calling the function and then passing it in, all is fine... but when I let the function do

if(pointer !=0)
delete[] pointer;

pointer = new type[something];
 
then after calling the function, when I want to access it, I get access violation... Why can''t I make my function delete and create a new pointer ?
Comrade, Listen! The Glorious Commonwealth's first Airship has been compromised! Who is the saboteur? Who can be saved? Uncover what the passengers are hiding and write the grisly conclusion of its final hours in an open-ended, player-driven adventure. Dziekujemy! -- Karaski: What Goes Up...
Advertisement
this is because of the way pointers are passed to functions. Pointers are still passed by value, that is the function has a local variable that is a pointer and it takes on the value (address of variable pointed to) of the pointer passed to it. Therefore, what you are doing is deleting what is being pointed to (by both the local pointer and pointer from the calling code) and then calling new for the local pointer only. This will not affect the pointer in the calling code and therefore when you access it after the fuinction terminates, you are accessing a deleted pointer (undefined) and hence the violation.

A solution would be to return the pointer from the function after you have called new and re-assign to the original pointer in the calling code.
Either that or send a pointer to the pointer.

So you have 2 options.
Return the new pointer:
type * f(type * pointer) {  // ...  return pointer;}// usage:somePointer = f(somePointer); 

or use a pointer to a pointer:
return_type f(type ** pointer) {  localPointer = *pointer;  // work with localPointer;}// usage:f(&somePointer); 
Option 3
reference to a pointer. just add a little & and all should be well.

returntype f(type *& pointer){
}
Thanks guys!
Comrade, Listen! The Glorious Commonwealth's first Airship has been compromised! Who is the saboteur? Who can be saved? Uncover what the passengers are hiding and write the grisly conclusion of its final hours in an open-ended, player-driven adventure. Dziekujemy! -- Karaski: What Goes Up...

This topic is closed to new replies.

Advertisement