返回主函数C 时,类中的值会破坏

values in class destroyed when getting back to main function c++

本文关键字:函数 返回      更新时间:2023-10-16

我在C 中的代码中有问题。我有一个正在使用的类数据架构,尤其是它的方法,其方法getAllCreaturesByLevel定义为以下内容:

Class DataStructure;
StatusType DataStructure::GetAllCreaturesByLevel(int magiID, int **creatures, int *numOfCreatures);

此方法从主函数中接收指针,并回馈有关其正在使用的对象的一些统计信息。

要从主函数中使用此方法,我调用一个函数,该函数将通过主函数传递指针,将对象从void*施加到数据架构*,然后调用其方法getAllCreaturesBylevel。此功能定义如下:

 StatusType GetAllCreaturesByLevel(void *DS, int magiID, int **creatures, int *numOfCreatures){
     if((DS == NULL)||(creatures == NULL)||(magiID == 0)||(numOfCreatures == NULL)){
        return INVALID_INPUT;
      }
    return ((DataStructure*)DS)->GetAllCreaturesByLevel(magiID, creatures, numOfCreatures);
}

该代码在此功能中完美工作。问题是回到主要:指针还给正确的值,但是对象中的所有数据都会更改并转换为垃圾值。

这个错误的原因是什么?

在我使用的方法中:

 int *creaturesArray = new int[*numOfCreatures];

并在"生物数组"中输入值:

for(int i = 0; i < *numOfCreatures; i++) {
     creatures[i] = &creaturesArray[i];
}

问题是组装。在从GetallCreaturesByLevel返回主的返回中,堆栈比进入功能时大,因此DS在以前的堆栈中不在同一位置。结果,投入DS的价值不是它的真实价值,而是"生物数组中的地址"之一。

解决方案是:

 int *creatures = new int[*numOfCreatures];

和原样返回生物,而无需在途中使用其他数组。