Assigning value to a char* in a function

Jan 28, 2015 at 1:20pm
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!!!"
Jan 28, 2015 at 1:30pm
What cc is pointing to? Where do you allocated memory for it to use?
Jan 28, 2015 at 1:38pm
Oh, dear. It compiles now. Thanks.
Last edited on Jan 28, 2015 at 1:38pm
Topic archived. No new replies allowed.