I'm wondering if there's any way to shift all characters from an index one position to the right, given that there is enough space allocated for it.
I got hints by my teacher that it can be done without an auxiliary variable and using the <cstring> library.
I tried:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100] = "Welcome to hell!";
strcpy(str+4, str+3);
cout << str; //Welccccccco hell!!
//Expected: Welccome to hell (to double the c so i can insert whitespace)
return 0;
}
I know that this function works with pointers as parameters, so calling it with the same string can mess things up. But is it possible in a way? I found that strcpy(s+i, s+j) gives an unexpected result if i > j. Why? Also, what's the alternative?
As was mentioned in the comments, you get undefined behaviour when using strcpy with overlapping ranges.
From https://cplusplus.com/reference/cstring/strcpy/
To see why this is an issue, we can look at some of the implementations of
strcpydiscussed in this question, and see that the code copies from the source buffer to the destination buffer until the null terminator character'\0'is reached. When callingstrcpy(str+3, str+4), you are always copying the same character, then advancing and reading again the same character you just copied, so the null terminator is never reached.Perhaps there is some difference or safety check in the implementation of
strcpyyou are using, as it does not overwrite the entire string, and stops after some time. Or perhaps this is the result of compiler optimizations, which are allowed to assume you don't do things the library functions say not to do (i.e. that your code does not invoke undefined behaviour).It's not clear from your question whether your teacher suggests using other tools in
<cstring>to write code to accomplish your goal, or whether your teacher thinks that there is an exact function which already does what you want.I would suggest that rather than starting from the middle of the string, you start at the end, and move all characters down one, to leave the doubling you desire. If the purpose of doing this shift is always to insert a space, you could build this space insertion into the same function as well.
As an aside, if you are working in C++, it is typically best to avoid C-style strings unless absolutely necessary. You should instead prefer using the standard library's
std::string.