返回主函数C 时,类中的值会破坏
values in class destroyed when getting back to main function c++
我在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];
和原样返回生物,而无需在途中使用其他数组。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量