Assigning value to a char* in a function

This code makes my program crash:

1
2
3
4
5
void copy(char* cp, int n) {
  for(int i=0; i < n; ++i) {
    *(cp + i) = data[i];
  }
}


I'm trying to implements std::string's copy function.

-> data is a member of my class: std::vector<char> data
-> cp is the char* which is supposed to receive the first n chars of data

Is my approach legit or is this bound to fail? Alternatively I thought of allocating some space for a char[], filling that one with values and then making the char* point to it.


If the above is correct, here is how I call copy() - the error might be here instead?:
1
2
char* cc;
s.copy(cc, 4);


-> s is an object of my class Str which holds "Hello World!!!"
What cc is pointing to? Where do you allocated memory for it to use?
Oh, dear. It compiles now. Thanks.
Last edited on
Topic archived. No new replies allowed.