Reputation: 165
I'm trying to set up some generic functions in C++ to allocate memory dynamically, and this is what I got to so far:
char* init_char(uint64_t A, const char* init){
char* ptr = new char[A];
memset(ptr, '\0', A*sizeof(char));
if(init != NULL)
strcpy(ptr, init);
return ptr;
}
char** init_char(uint64_t A, uint64_t B, const char* init){
char** ptr = new char*[A];
for(uint64_t a = 0; a < A; a++)
ptr[a] = init_char(B, init);
return ptr;
}
The idea is that you just pass the dimensions (A, B) and the initialization string (init) and it return an array with all the memory allocated. However, while the first one seems to work properly, the second one returns a NULL pointer.
I've looked around but no good. Actually in some other post (Function for Dynamic Memory allocation) they seem to do something quite similar. Am I missing something here?
thanks,
Upvotes: 0
Views: 167
Reputation: 6883
your error is not to use c++.
your problem can be reduced to:
std::string initStr("initialitation string");
int a = 10;
std::vector<std::string> myStringArray(a, initStr);
Upvotes: 4