I need to write function which duplicates a string. I didn't try to compile this one, but I think it works well:
Maybe you say "why this way". My goal is - not to allocate more memory than needed. If psource is single character, so function'd allocate two bytes (character and terminator, each one byte long, that's right, isn't it?), not more.Code:char* clonestring(char* psource) { int length = strlen(psource) + 1; //+ 1 for NULL, that's right, isn't it? char *pclone = new char[length]; for (int i = 0; i < length; i++) pclone[i] = psource[i]; //I don't like this line :( return pclone; } //example of usage: int main() { char short[] = "a"; char long[] = "aaaaaaaaaaa"; char *copyofshort = clonestring(short); //new memory (2 bytes) allocated, same value as short char *copyoflong = clonestring(long); //new memory (12 bytes) allocated, same value as short return 0; }
Can I replace the line with for statement with something shorter? Assignment or something??
Or maybe this whole function could be written any other, more optimal way???



LinkBack URL
About LinkBacks



