From 3ac00a66ff5e38c389578c6eb83190a175e616aa Mon Sep 17 00:00:00 2001 From: neingeist Date: Sat, 23 Aug 2014 11:13:53 +0200 Subject: [PATCH] how to convert vector to const char** --- .gitignore | 1 + CMakeLists.txt | 1 + ohai-const-strings.cpp | 68 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 ohai-const-strings.cpp diff --git a/.gitignore b/.gitignore index 62207b3..9a0f16a 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ future return-type-deduction division poly +ohai-const-strings diff --git a/CMakeLists.txt b/CMakeLists.txt index b9b388d..aa7936b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,6 +20,7 @@ add_executable(bad_alloc bad_alloc.cpp) add_executable(rtti rtti.cpp) add_executable(poly poly.cpp) add_executable(division division.cpp) +add_executable(ohai-const-strings ohai-const-strings.cpp) add_executable(future future.cpp) set_target_properties(future PROPERTIES LINK_FLAGS "-pthread") diff --git a/ohai-const-strings.cpp b/ohai-const-strings.cpp new file mode 100644 index 0000000..d56c155 --- /dev/null +++ b/ohai-const-strings.cpp @@ -0,0 +1,68 @@ +// how to convert std::vector to const char**? + +#include + +#include +#include +#include + +void print_strings(const std::vector strings) { + using std::cout; + using std::endl; + + cout << "== Printing some std::vector strings:" << endl; + for (const std::string &s : strings) { + cout << s << endl; + } +} + +const char** convert_to_c(const std::vector strings) { + // Note: perfectly fine to "new" const char*. + const char** strings_c = new const char*[strings.size()+1]; + for (size_t i = 0; i < strings.size(); ++i) { + // XXX No need to copy the string here. + char* string_c = new char[strings.at(i).size()+1]; + strncpy(string_c, strings.at(i).c_str(), strings.at(i).size()+1); + strings_c[i] = string_c; + } + strings_c[strings.size()] = NULL; + + return strings_c; +} + +void free_c(const char** strings_c) { + for (size_t i = 0; strings_c[i] != NULL; ++i) { + delete[] strings_c[i]; + } + delete[] strings_c; +} + +void print_strings_c(const char** strings_c) { + using std::cout; + using std::endl; + + cout << "== Printing some const char** strings:" << endl; + for (size_t i = 0; strings_c[i] != NULL; ++i) { + cout << strings_c[i] << endl; + } +} + +void foo(const char* string) { + printf("foo: %s\n", string); +} + +int main() { + foo("foo"); + char* bar = new char[4]; + strncpy(bar, "bar", 4); + foo(bar); + delete[] bar; + + std::vector some_strings = { "just", "some", "strings", "here" }; + print_strings(some_strings); + + const char **some_strings_c = convert_to_c(some_strings); + + print_strings_c(some_strings_c); + free_c(some_strings_c); +}