You have some kind of a mixture of C and C ++ programming styles. Therefore, if it were not for the presence of the operator new , then it would be possible to conclude that the program is written in C.
As for the function. Function parameters are local variables of the function. The function deals with a copy of the value of the original str argument declared in main . Therefore, this sentence in the function
str = buf;
does not change the value of the original pointer declared in main . It changes the value of the local variable of the function str same name.
At the same time, the function inside the function deletes the memory pointed to by the source pointer. Therefore, after exiting the function, the initial str pointer will contain an incorrect value, and the program will have undefined behavior, trying to access the memory addressed by this pointer.
It is necessary to pass the first argument to the function either by reference or through a pointer to the argument.
When dealing with strings, there is generally no need to use the memcpy function. This function is for copying raw bytes. You'd better use the standard strcpy function.
All standard functions that deal with strings usually return a pointer to the result string. Therefore, you should follow this rule.
Below is a sample program that shows how a function can be implemented when the first parameter is declared as a pointer to the original argument. An alternative would be to declare the first parameter as a link.
char * insert( char * &s, char c, size_t pos ); ^^^^^^^^^
Keep in mind that the standard strlen function has the size_t return type as well as the sizeof operator. Therefore, you should declare variables with this type that will store the corresponding values returned by this function. Otherwise, for very large lines, there may also be a problem with the program’s undefined behavior.
And besides, you should check in the function the correctness of the given position to insert a new element. If the position is out of the allowed range, the function can simply return the original string without changing it.
Here is the demo itself
#include <cstdio> #include <cstring> char * insert( char **s, char c, size_t pos ) { size_t n = std::strlen( *s ); if ( !( n < pos ) ) { n += 2; char *tmp = new char[ n ]; size_t i = 0; for ( ; i < pos; i++ ) tmp[i] = s[0][i]; tmp[i++] = c; for ( ; i < n; i++ ) tmp[i] = s[0][i-1]; delete [] *s; *s = tmp; } return *s; } int main() { char* str = new char[7]; std::strcpy( str, "abcefg" ); std::printf( "str: [%s]\n", str ); std::printf( "str: [%s]\n", insert( &str, 'd', 3 ) ); delete [] str; return 0; }
Its output to the console
str: [abcefg] str: [abcdefg]
It is advisable to free the allocated memory at the end of the program.