gpt4 book ai didi

c++ - 内存堆,动态设置数组

转载 作者:行者123 更新时间:2023-11-28 05:11:34 24 4
gpt4 key购买 nike

我有一个问题,我认为它与堆内存有关。将不胜感激帮助。

这是在部落标题中:

Survivor* SurvivorsArray = new Survivor[MaxSurvivorsInTribe]; 

这是我的问题。当我写

Survivor* SurvivorsArray = new Survivor[MaxSurvivorsInTribe]; 

我遇到了这个问题:

EXE3.exe has triggered a breakpoint.

这是将我的输入代码用于:

    if (_crtheap == 0) {
#if !defined (_CRT_APP) || defined (_DEBUG)
_FF_MSGBANNER(); /* write run-time error banner */
_NMSG_WRITE(_RT_CRT_NOTINIT); /* write message */
#endif /* !defined (_CRT_APP) || defined (_DEBUG) */
__crtExitProcess(255); /* normally _exit(255) */
}

return HeapAlloc(_crtheap, 0, size ? size : 1);
}

但是如果我写:

Survivor* SurvivorsArray = new Survivor[100]; 

所以它的工作没有错误。

目前它仅在我设置预设数组时有效,但如果我想从用户那里获取数组大小,则会出现错误。

主要:

#include <iostream>
#include <string>
using namespace std;

#include "survivor.h"
#include "tribe.h"
int main(){
Tribe t1;
Tribe t2;
char nameTribe1[20];
int maxTribe1;
cout << "Enter name of first tribe: " << endl;
cin >> nameTribe1;
cout << "Enter max of survivors to first tribe(max 100): " << endl;
cin >> maxTribe1;
t1.tribe(nameTribe1, maxTribe1);

char nameTribe2[20];
int maxTribe2;

cout << "Enter name of second tribe: " << endl;
cin >> nameTribe2;
cout << "Enter max of survivors to second tribe(max 100): " << endl;
cin >> maxTribe2;
t2.tribe(nameTribe2, maxTribe2);
return 0;
}

幸存者头:

class Survivor{

public:

char NameOfSurvivor[20];
int Age;
double StartWidgth;
double FinalWidgth;

void survivor(char name[20], int age, double sWidgth);
};

#endif

幸存者cpp:

#include "survivor.h"
#include <iostream>

using namespace std;
void Survivor::survivor(char name[20], int age, double sWidgth){
for (int i = 0; i < 20; i++)
NameOfSurvivor[i] = name[i];

Age = age;
StartWidgth = sWidgth;
FinalWidgth = -1;
}//end survivor

部落首领:

class Tribe{

public:

char NameOfTribe[20];
int MaxSurvivorsInTribe;
**Survivor* SurvivorsArray = new Survivor[MaxSurvivorsInTribe];**
int NumbersOfSurvivorsInTribe;
void tribe(char name[20], int maxSurvivor);

};

#endif

部落 cpp:

#include "tribe.h"
#include <string>
#include <iostream>

using namespace std;

void Tribe::tribe(char name[20], int maxSurvivor){
for (int i = 0; i < 20; i++)
NameOfTribe[i] = name[i];


for (int i = 0; i < maxSurvivor; i++){
for (int j = 0; j < 20; j++){
SurvivorsArray[i].NameOfSurvivor[j] = ' ';
}//end for
SurvivorsArray[i].Age = 0;
SurvivorsArray[i].StartWidgth = 0;
SurvivorsArray[i].FinalWidgth = 0;

MaxSurvivorsInTribe = maxSurvivor;
NumbersOfSurvivorsInTribe = 0;
}//end for
}//end tribe

谢谢。

最佳答案

您不能在类声明中执行动态分配。将数组分配移至 Tribe 构造函数。

顺便说一下,除非出于某种原因禁止您使用 STL,否则使用 vector 而不是数组会好得多。

关于c++ - 内存堆,动态设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43402666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com