How to convert TArray<'FString> to char **?


How to convert TArray<'FString> to char ** ?


This should do it:

TArray<FString> a;

// ...

char [255][a.Num()] b;

for (int i=0; i<a.Num(); i++)
   b[i] = TCHAR_TO_ANSI(*a[i]);

TCHAR_TO_ANSI can’t be used to store variable, check the doc on that macro.

I find a solution :

const char ** achar = new const char*outArray.Num();

int32 i = 0;

while (i < outArray.Num()) {
achar[i] = (char*)outArray[i].GetCharArray().GetData();

Please don’t advise people to use unsafe memory allocation - this code WILL leak memory without a matching call to delete!

First, please take note that a const char ** can also be written as const char * [], as a pointer in C++ can also act as an array, and vice versa.
Where possible if you can please use std::vector, or another safe type.
However, this snippet should suit your needs.

	TArray<FString> YourArrayOfFString;
	std::vector<std::string> StringArray;
	for(int I =0; I < YourArrayOfFString.Num(); I++)
	std::vector<const char *> CharPtrArray;
	for (int I = 0; I < StringArray.size(); I++)
    const char **  ThePointerYouWant=;

Please take note that as this contains char Pointers, the final data pointer is only valid as long as StringArray and CharPtrArray exist, if they leave scope, the code will have undefined behaviour

As a side note, to quote the C++ creator Bjarn,

Any code that has a New must have a Delete, and any code that has a Delete most likely has a bug!

In short, avoid using the “New” keyword in C++ unless you are 100% certain it will not cause a memory leak or other error.

1 Like