Reputation: 4853
If I had a function defined arbitrarily like:
char* myfunction(int, int[]);
which, as shown, returns a character pointer. Do you have to write in the calling function something like:
char *ptr = myfunction( ... );
Or is there a way to use the pointer that is returned by the function without creating another pointer to the one returned?
I ask because, given how I described above, you essentially have a pointer returned, and another pointer assigned to that one. Thus, you then have an unused pointer (the one returned by the function) taking up memory.
If there is no way to explicitly use the pointer that is returned, is there a way to assign a new pointer to the returned pointer and free the unused one?
Upvotes: 2
Views: 124
Reputation: 44706
A pointer is a really small thing. It's just a representation of the address of an object. You shouldn't be concerned about creating extra copies of a pointer (it's like creating an extra int).
char* foo() {
char* bar;
// some stuff that mallocs a value and assigns to bar
return bar;
}
char* x = foo();
In the simplified example above, the bar pointer is created on the stack, and the code in the comments points it at some memory in the heap (with a Malloc or something). When the function foo() is evaluated, the value of the pointer (e.g. The address of the memory) is popped off the stack and assigned to x. There is no unused pointer hanging around, it's just been reassigned. The memory that it points to remains exactly where it is and isn't duplicated.
You aren't creating extra copies of the memory that the pointer is pointing to. In fact, that's a large reason to pref pointers, because it involves copying less.
Upvotes: 3
Reputation: 3172
The pointer that is returned by the function doesn't waste memory as you state. When the function returns, and as soon as the affectation ptr = myfunction(...);
is done, the returned value doesn't exist anymore in memory.
But to answer your question, yes you can use the returned pointer directly, without a temporary variable. Although it is a rvalue (you can't do myfunction() = NULL
for example), the location it's pointing to is at your disposal : *myfunction() = 3
is valid, granted the pointer returned is valid.
I prefer using a temporary variable, as you can reuse the value in 2 or more expressions, and it is far more readable in my opinion.
Upvotes: 2