Visual c++ 如何将字符串^放入2d字符数组中?

Visual c++ 如何将字符串^放入2d字符数组中?,visual-c++,Visual C++,我正在尝试将字符从System::String^复制到矩形字符数组 首先,我尝试了:以及其他一些代码。与问题无关 char name[25][21]; ... void savedata(int x, System::String ^ a){ //x is the student #, a is the name int b; using namespace System::Runtime::InteropServices; // for class Marshal

我正在尝试将字符从System::String^复制到矩形字符数组

首先,我尝试了:以及其他一些代码。与问题无关

char name[25][21]; 

...

void savedata(int x, System::String ^ a){ //x is the student #, a is the name
    int b;
    using namespace System::Runtime::InteropServices; // for class Marshal
    char* buffer((char*)(void*)Marshal::StringToHGlobalAnsi(a));
    x--; //So we write buffer[b] at data[0][b] when int x is 1
    for(b = 0; b < 21; b++){
        data[x][b] = buffer[b];
    };
}
当我试图运行和调试它时,发生了一个类型为“System.AccessViolationException”的未处理异常

是否有更简单/更好的方法将字符串^放入二维字符数组,如果没有,我在这里做错了什么?

您应该调用.ToPointer将StringToHGlobalAnsi的结果转换为可以转换为字符的内容*

您还应该在StringTohGlobalAsi的结果上调用FreeHGlobal,或者您可以从char*重新创建IntPtr