memcpy works fine when you're moving data from one chunk of memory to another, but when you use it on the same piece of memory, it can fail. How?
Imagine you are at element[0]. First you put e[0] into e[1],
then e[1] into e[2]...uhoh! You already overwrote e[1]! So to get it to work, you have to either write a reverse_copy routine (which starts from the end), or else use some swapping technique...
Code:
#include <iostream>
using namespace std;
void
print(const char * msg, char ** arp, int lng)
{
cout << (msg ? msg : "") << endl;
for(int n = 0; n < lng; ++n)
cout << arp[n] << endl;
cin.get();
}
bool
insert(char ** arp, int lng, char * adr, int where)
{
if(where >= lng)
return false;
char * t1, * t2 = arp[where];
for(int n = where+1; n < lng; ++n)
{
t1 = arp[n];
arp[n] = t2;
t2 = t1;
}
arp[where] = adr;
return true;
}
int
main(int argc, char *argv[])
{
const int size = 10;
char str[size+1] = "0123456789";
char * index[size] =
{
&str[0],
&str[0],
&str[0],
&str[0],
&str[0],
&str[0],
&str[0],
&str[0],
&str[0],
&str[0]
};
print("Start:", index, size);
insert(index, size, &str[4], 4);
print("Finish:", index, size);
return 0;
}