| vijkrr (79) | |
|
Hi, I need few clarification in returning pointers.. Assume a common API char* itoa(int); If I want to write a same type of funciton, I need to return the char* How to implement this, sine char* if i declare in local then that address if of local scope. If I use new then caller needs to delete. Can any one explain how this is been implemented?? thanks | |
|
|
|
| kbw (5520) | |||||
|
Returning pointers isn't the problem. It's managing the memory that's being point, that is. Although atoi is
you'll find you need to pass a buffer to itoa:
You're right to identify a problem here. By and large, if you need a string type, just use std::string and forget about pointers. If your char* is a pointer to something else, you have to make sure that it doesn't point to local memory that'll disappear on return. | |||||
|
|
|||||
| ajh32 (163) | |||||
As described by @kbw above, the itoa function provided by the standard library has the following three arguments:
argv[0] is the integer to be converted argv[1] is a pointer to a char array argv[2] is an integer to tell the itoa function the number base to use So the problem with the pointer to the memory is overcome by using a memory location the caller has allocated:
If you debug through the above code, you will see that the address to the char array we have declared using the variable named 'buffer' being passed through to itoa function is the same address that is returned by the function and allocated to the char* pointer we have named 'result'. So the memory the result of the function exists outside of the function itself and is therefor not lost like a local variable within itoa would be. I hope that explains this function. So, you either provide a particular function with a pointer to the memory to be used as above, OR you can use a member variable inside a struct or class in which the function exists. HTH Andrew | |||||
|
|
|||||