When the form is closed, the Access violation writing location error occurs.

Connection of modules and structure:

#include <iostream> #include <conio.h> #include <fstream> #include <string> #include <stdio.h> #include <stdlib.h> #include <sstream> #include <stdexcept> struct team { char name[50]; int score; }; team *teams; using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; using namespace std; using namespace System::Runtime::InteropServices; 

MarshalString function:

  void MarshalString ( String ^ s, string& os ) { using namespace Runtime::InteropServices; const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer(); os = chars; Marshal::FreeHGlobal(IntPtr((void*)chars)); } 

Code:

 void readFromDGV() { try { for(int i=0;i<dataGridView1->RowCount-1;i++) { String^ tname=Convert::ToString(dataGridView1->Rows[i]->Cells[0]->Value->ToString()); string sname; MarshalString(tname,sname); strncpy_s(teams[i].name,sname.c_str(),sizeof(teams[i].name)); teams[i].score=Convert::ToInt32(dataGridView1->Rows[i]->Cells[1]->Value); } } catch (Exception ^ex){}; } void enterIntoDGV() { try { for(int i=1;i<dataGridView1->RowCount;i++) { string str0(teams[i].name); String ^st0=gcnew String(str0.c_str()); dataGridView1->Rows[i-1]->Cells[0]->Value=st0; dataGridView1->Rows[i-1]->Cells[1]->Value=teams[i].score.ToString(); } } catch (Exception ^ex){}; } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { int n=dataGridView1->RowCount-1; teams=new team[n]; readFromDGV(); team temp; for (int i = 0; i < dataGridView1->RowCount; i++) { for (int j = i + 1; j < dataGridView1->RowCount; j++) { if (teams[i].score>teams[j].score) { temp = teams[j]; teams[j] = teams[i]; teams[i] = temp; } } } enterIntoDGV(); } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { readFromDGV(); team temp; for (int i = 0; i < dataGridView1->RowCount; i++) { for (int j = i + 1; j < dataGridView1->RowCount; j++) { if (teams[i].score>teams[j].score) { temp = teams[j]; for (int k = j; k>i; k--) teams[k] = teams[k - 1]; teams[i] = temp; } } } enterIntoDGV(); } 

Mistake:

enter image description here

    0