I. SolutionFunction return pointerMethods
1. Returns a pointer to a String constant.
Example:
char* func(){ rturn "Only work for simple strings";}
Advantages:Simple
Disadvantages:This method is useless if you need to calculate the string content. If you need to modify the returned string in the future, you will also have trouble!
2. Use an array declared globally.
Example:
char my_global_array[255];char* func(){ my_global_array[0] = ‘0‘; return my_global_array;}
Advantages:It is applicable to self-created strings and is easy to use.
Disadvantages:Anyone may modify this global array at any time, and the next call of this function will overwrite the content of this array.
3. Use static arrays.
Example:
char* func(){ static char buff[20]; buff[0] = ‘0‘; return buff;}
Advantages:It can prevent anyone from modifying this array. Only a function with a pointer to this array (passed to it through parameters) can modify this static array.
Disadvantages:HoweverThe next call will overwrite the content of this array.So the caller must use or back up the contents of the array before this. Like global data, it is a waste of memory space if a large buffer is idle.
4. explicitly allocate some memory to save the returned value.
Example:
char* func(){ char *s = malloc(120); ... return s;}
Advantages:This method has the advantage of a static array and creates a new buffer every time it is called. All future calls of this function will not overwrite the previous return values.It is applicable to multi-threaded code.
Disadvantages:Programmers must take responsibility for memory management.
5. The caller is required to allocate a memory class to save the return value of the function. Programmers malloc and free
Example:
void func(char* result, int size){ ... strncpy(result, "that‘d be in the data segment, Bob", size);}buffer = malloc(size);func(buffer, size);...free(buffer);
Advantages:Memory Management is relatively easy.
Disadvantages:Programmers still need to manage their own memory, but compared to the first 4th methods, malloc and free are paired to facilitate memory management.
Ii. Statements
2.1 some cannot
1. the return value of a function cannot be a function; Foo () is invalid.
2. the return value of the function cannot be an array; Foo () [0] is invalid.
3. There cannot be a function in the array; Foo [] () is invalid.
One of C expert Programming