Dec 21, 2015 at 9:03pm UTC
First of all this is a part of an exercise.
Is it possible to create a pointer to an arbitrarily long word stored as an array of characters on free store using
new
without predefining huge buffer to be sure that all the characters will fit there?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <string>
void cpy(char * buffer, const std::string& str){
int i = 0;
for (; i < str.size(); ++i) {
buffer[i] = str[i];
}
buffer[i] = '\0' ;
}
int main(){
char * buffer = new char [1000];
std::string str;
std::cin >> str;
cpy(buffer, str);
return 0;
}
Is there better way than this? Also now I cant even store something bigger than 1000 characters not that I think I would need to very often.
Last edited on Dec 21, 2015 at 9:03pm UTC
Dec 21, 2015 at 9:07pm UTC
Instead of this:
char * buffer = new char [1000];
have this:
char * buffer = new char [size_needed];
where you calculate size_needed during the programs execution.
Obviously, if this wasn't an exercise just for the fun of it, you would just use a string.
Dec 22, 2015 at 9:06am UTC
Cool, tnx a lot guys. I didn't notice that when using new, size of an array doesn't have to be a constant expression. TY very much :)