I couldn't find a reason for this problem.
The function getfruits returns a pointer to an array of pointes of c-style strings. Main tries to access the c-style strings.
using namespace System;
#pragma managed
void getfruits(char ***list, int* count)
{
char *txt[] =
{
"apple",
"orange",
"pears",
"banana",
};
*list = txt;
*count = 4;
}
#pragma managed
int main(array<System::String ^> ^args)
{
char **lst; int cnt;
getfruits(&lst,&cnt);
char *t; int i;
String^ s;
for (i=0; i<cnt; i++)
{
t = lst[i]; //t = <undefined value>
s = gcnew String(t);
Console::WriteLine("Fruit = {0}", s);
};
Console::ReadKey();
return 0;
}
But it gets instead of pointers to the c-style strings.
Eventually,
An unhandled exception of type 'System.AccessViolationException' occurred in arraysandclasses.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
What's going wrong? Can somebody point out anything? The code should simply compile if copied and pasted. Thanks in advance.
You've returned the address of a local array and used it. That's undefined behavior. txt
has automatic storage duration and gets destroyed as soon as you leave the getfruit
function. But you keep a pointer to it and use it, but the pointed memory no longer contains a living object. I suggest that you should perhaps read a good C++ book.