Activate all warnings (e.g. with -Wall):
main.cpp:24:15: warning: deprecated conversion from string constant to 'char*'
char* b = "hey are you ready";
^
The easiest solution would be to use an array of characters instead:
char b[] = "hey are you ready"; // more characters than your original one
Concerning copy: you want to check whether source actually contains n characters or stop beforehand:
void cpy(char * dest, const char* source, int n)
{
for(int i = 0; *source != '\0' && i < n; ++i)
// copies n characters or until source has been copied completely
*dest++ = *source++;
}
*dest = '\0';
}
Why is this necessary
In your original code, b is a pointer to characters. Now, pointers can point anywhere aka store any memory addresses, even of those memory sections you're not allowed to change. A string literal is stored in the constant data section of your program*. You're not allowed to alter that stuff. But you do that either way and end up with a segmentation fault.
Therefore, you need to ensure that you alter a version that doesn't reside in the read-only section of your program. The array version does exactly that: it initializes a new array, which has the same content as your original literal.
And by the way, your edit has also undefined behavior. Now b points to a single character. If you were to copy more than one character to the location b is addressing, you would write to some memory, but not the one that actually belongs to b. This results in undefined behavior.
The bottom note is: don't trick the compiler with such things.
Using C++, not C
However, there are some other problems with your code. For starters, it's mostly C. The only part where you actually use C++ is cout. If you were to use std::string, you wouldn't have those problems beforehand:
#include <iostream>
#include <string>
int main(){
const std::string a = "honey singh";
std::string b = "hey are you ready";
const int n = 5;
b = a.substr(0, n);
}
As you can see, your copy is already part of the standard library, namely std::string::substr
Note that there were some other broken things in your original code, such as copy having quadratic runtime instead of linear, copy copying too much into too little memory, etc.