C++ 中的结构数组(Rad Studio 10.1 - Android 的应用程序)

Struct Array in C++ (Rad Studio 10.1 - App for Android)

对于 windows,我通常在 C++ 中将结构数组广泛用于数组,并分别在构造函数和析构函数中通过 new 和 delete 分配内存。

这是我的第一个 Android 应用程序。

应用程序崩溃,自从我从一个简单的数组更改了我的第一个数组 在头文件中定义为 float AccelZ[1000] 用作 AccelZ[i]

到头文件中定义的结构数组,并在 FormCreate 和 FormDestroy 事件中使用 new 和 delete。 并用作 AccelArray[i]->Z

Android 中没有使用结构数组吗?但如果是这样的话,我会预料到会出现编译错误。

谢谢

现在用例子编辑:

在头文件中:

const int MAXTIMESTEPS = 20000;  
struct AccelerationRecord  
{  
    float Z;  
};  

在 Public 下:

AccelerationRecord* Acceleration[MAXTIMESTEPS];

在 FormCreate 下的 .cpp 文件中在 Windows 中我会把它放在构造函数中,但这对 Android App 不起作用(我是 Android Apps 的新手)

void __fastcall TTabbedwithNavigationForm::FormCreate(TObject *Sender)
{  
    for (int i; i < MAXTIMESTEPS; i++)  
      Acceleration[i] = new AccelerationRecord;  
>>snip other code    
}  

在 FormDestroy 下(用于在 Windows App 中将其放在析构函数中)

void __fastcall TTabbedwithNavigationForm::FormDestroy(TObject *Sender)  
{  
    for (int i; i < MAXTIMESTEPS; i++)  
      delete Acceleration[i];  
}  

稍后在应用程序中,第一次用作

if (MotionSensor1->Sensor-
>AvailableProperties.Contains(TCustomMotionSensor::TProperty::AccelerationZ))  
{  
lbAccelerationZ->Text = lbAccelerationZ->Text.sprintf(L"Acceleration Z: %6.2f",MotionSensor1->Sensor->AccelerationZ+1);  
Counter += 1;  
Acceleration[Counter]->Z = MotionSensor1->Sensor->AccelerationZ+1;  
//crashes at this line in debug mode  
>> snip other code  
}  

首先:

for (int i; i < MAXTIMESTEPS; i++)

应该是

for (int i=0; i < MAXTIMESTEPS; i++)

对于未初始化的 i,您可以越界访问数组,从而导致崩溃。您的也是如此:

Counter += 1;

我没有看到绑定检查也没有初始化所以天知道 Counter 的值是多少。

其次我比较习惯这个:

// "globals"
const int MAXTIMESTEPS = 20000; 
struct AccelerationRecord  
    {  
    float Z;  
    };  
AccelerationRecord* Acceleration=NULL;

// init
Acceleration = new AccelerationRecord[MAXTIMESTEPS];

// here do your stuff on AccelerationRecord[i]
AccelerationRecord[7].z=-1.5;

// exit
delete[] Acceleration;

单个 new/delete[] 比为每条记录调用它要好得多,原因有二。首先,您减轻了内存管理器的压力(更少的开销),其次,您获得了连续的内存块,并记住相同内容的单个指针而不是 20000 使用更少的内存并具有更快和线性的访问...