int Insert(char* Str1, char* Str2, int n)
{
stringCopy(Str3, Str1, n);
stringCopy(Str3, Str2, lenS2);
stringCopy(Str3, Str1 + n, lenS1 -lenS2);
Str1 = Str3; // Pointer assignment is OK but in main function, I have old string..
return 1;
}
int main()
{
char* Str1 = "Blahblahblah";
char* Str2 = "123";
Insert(Str1, Str2, 4);
printf_s("%s\n", Str1); // I have old string instead new string
return 0;
}
Line 10 is just overwriting Str1, which is a local variable. If you need to change a pointer in main, you need two levels of indirection to change the pointer within another function.
Changing the value of Str1 itself will have no effect outside the local function. It's the same thing as if Str1 were an int. Assigning var = 42; will have no effect outside the local function.
So is Str3 a global variable? That's the only way out of this mess, as you have it. print Str3, not Str1. Otherwise, as you currently have it, what you're doing doesn't make sense to me.
PS, just because I'm bored, I made a modified version of strcat.
how is the return value used? pointers are just integers...
you could return it in the return value, 0 (null in C) for errors etc, as another way out.
then it would just be
newstr = insert(blah blah). I don't think you even have to cast it, in C, do you? I think its friendly to cast it anyway but C people get bent out of shape over unnecessary casting.
If you don't then you are changing the address to which Str1 points and expect the calling program to know this and free the memory - which is not good. Instead, rather than insert() returning an int, have it return a char* pointing to the new string.
The address pointed to by Str1 can't be changed by Insert(). As you are not passing as an argument the size of the Str1 buffer, this means that it has to be assumed that the memory pointed to by Str1 is large enough to contain the final string - which is dangerous for buffer overflow issues.
Who devised this function definition - it's bad design!
Ah right, this whole time I wasn't considering making str1 itself point to an actual buffer and not just read-only memory. That would work and I think meet OP's reqs.
Edit:
Thank you, @Ganado, but your code is wrong.
Maybe English isn't your first language, so you are speaking incorrectly. My code being "wrong" means something different than my code not meeting your specific needs. If my code is wrong, tell me how it's wrong. The buffer being size 10 was intentional as a test.