returnint char*


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??

Returning pointers isn't the problem. It's managing the memory that's being point, that is.

Although atoi is
int itoa(const char *);

you'll find you need to pass a buffer to itoa:
char* itoa(int value, char* str, int base);
In this case, the buffer passed in as str is returned.

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.
As described by @kbw above, the itoa function provided by the standard library has the following three arguments:

int   char*   int

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:

int number(123);    // the number to convert
char buffer[10];      // the char array into which we are to ask itoa to put result
char* result = itoa(number, buffer, 10);   // calling itoa using base10 

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.


Topic archived. No new replies allowed.