Archived

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

Pointers, methods and new

This topic is 4947 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 ?

Share this post


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

Share this post


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

Share this post


Link to post
Share on other sites