I would like to perform the above mentioned operation, however I would like to make sure that the char array is exactly the same size with the string at hand.
So the real question is, how can I make an array with a size that is going to be determined in the run time?
6 Answers 6
allocating memory on the free store, and copying the string in one go:
std::string s("abcdef");
...
char* chars=strdup(s.c_str());
You need to free the memory manually, of course. Documentation e.g. on the man page. As @Loki mentions: freeing this memory is done through free(chars)
, not through delete
. Also, you need to include the <cstring>
header.
If you want to stay in the c++ world, use a vector
; it can be created with two iterators to copy it's data from, and will allocate on the heap, and will cleanup by itself. Isn't that a treat?
std::vector<char> vec( s.begin(), s.end() );
-
Now you have to pepper your code with free(). So it saves you one line here but makes the code much more complex as you have two different memory pools to manage.Loki Astari– Loki Astari2011年12月09日 19:50:59 +00:00Commented Dec 9, 2011 at 19:50
-
@LokiAstari: that is very true. I should have added that - personally I prefer the vector approach, though.xtofl– xtofl2011年12月09日 19:55:15 +00:00Commented Dec 9, 2011 at 19:55
-
Also, note that the OP said "make sure that the char array is exactly the same size with the string at hand"; if the
string
contains embedded null characters, then yourstd::vector<>
solution will work properly while yourstrdup
solution will not.ildjarn– ildjarn2011年12月09日 20:09:52 +00:00Commented Dec 9, 2011 at 20:09
You can create an array of size known at runtime with the "new" operator:
char* res = new char[str.size()+1];
strncpy(res, str.c_str(), str.size()+1);
-
1If the
string
contains any embedded null characters thenstrncpy
will truncate the data.memcpy
is more appropriate here, or a proper container such asstd::vector<>
.ildjarn– ildjarn2011年12月09日 19:55:49 +00:00Commented Dec 9, 2011 at 19:55
std::string s = "hello";
char* c = new char[s.length() + 1]; // '+ 1' is for trailing NULL character.
strcpy(c, s.c_str());
#include <string>
int main(int argc, char *argv[])
{
std::string random_data("This is a string");
char *array=new char[random_data.size()+1];
// do stuff
delete[] array;
return 0;
}
Try:
char* res = new char[str.size()+1](); // Note the () makes sure it is '0' filled.
std::copy(str.begin(), str.end(), res); // Don't need to copy the '0円' as underlying
// array already has '0円' at the end position.
...
delete [] res; // Must not forget to delete.
Or: (preferably)
std::vector<char> res(str.begin(), str.end());
Or: If all you want to do is call a C-unction:
str.c_str()
Use strlen() to find the length of the string, then malloc() a char array of that size.