#include <stdio.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <string.h>
#include <malloc.h>
/// <summary>
/// Adds strings to a vector
/// </summary>
void GetStrings(std::vector<std::string>& v){
v.push_back("Hi");
v.push_back("There");
v.push_back("Pal");
}
/// <summary>
/// Returns an array of character arrays (C strings)
/// and the array's length
/// </summary>
void GetStrings(char *** strings, int & size, bool clientFrees = false){
std::vector<std::string> sts; // stack allocated, no need to free
GetStrings(sts);
size = sts.size();
(*strings) = (char**)malloc(sizeof(char*) * size);
for (int n = 0; n < size; n++){
if (clientFrees){
(*strings)[n] = (char*)malloc(sizeof(char) * (sts[n].size()+1));
strncpy((*strings)[n], sts[n].c_str(), sts[n].size()+1);
}
else {
(*strings)[n] = (char*)sts[n].c_str();
}
}
}
int main()
{
// change this to see what happens when the client
// must free resources
bool clientFrees = true;
// define the out parameters
int size = 0;
char** strs = NULL;
// Get the strings
GetStrings(&strs, size, clientFrees);
// Inspect the out parameters
printf("size = %d\n", size);
for (int n = 0; n < size; n++){
printf("%s\n", (char*)strs[n]);
if (clientFrees){
free((char*)strs[n]);
}
}
// No control over the malloc, must free
free(strs);
return 0;
}