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

Hello

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

Thanks!

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();
i++;
}

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++)
	{
		StringArray.push_back(std::string(TCHAR_TO_UTF8(*(YourArrayOfFString[I]))));
	}
	std::vector<const char *> CharPtrArray;
	for (int I = 0; I < StringArray.size(); I++)
	{
		CharPtrArray.push_back(StringArray[I].c_str());
	}
    const char **  ThePointerYouWant= CharPtrArray.data();

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