【发布时间】:2022-01-07 04:48:54
【问题描述】:
我在学校有一个项目,需要制作一个包含机场数量和 Airport 数组(另一个结构)的 AirportManager 结构。我开始编写代码,但我遇到了机场数组的 malloc 问题。
到目前为止,我附加了我编写的代码,我遇到的问题是这些值没有保存在 AirportManager 的 airportArray 中。
//AirportManger Struct
typedef struct {
Airport* airportArray;
int airportAmount;
}AirportManager;
void initAirportManager(AirportManager* airportManager)
{
airportManager->airportAmount = 0;
airportManager->airportArray = (AirportManager*)malloc(0);
}
void addAirport(AirportManager* airportManager)
{
Airport airport;
printf("Enter Airport Name: ");
scanf("%s", airport.airportName);
printf("Enter Airport Address: ");
scanf("%s", airport.airportAddress);
airportManager->airportAmount++;
airportManager->airportArray = (Airport*)realloc(airportManager->airportArray, airportManager->airportAmount * sizeof(Airport));
airportManager->airportArray = airport;
}
//Airport Struct
typedef struct {
char airportName[MAX];
char airportAddress[MAX];
}Airport;
//Main
AirportManager airportManager;
initAirportManager(airportManager);
addAirport(&airportManager);
【问题讨论】:
-
airportManager->airportArray = realloc(...);后跟(无效)赋值airportManager->airportArray = airport。如果最后一个任务是有效的,你认为会发生什么?如果你有例如int a; a = 10; a = 20;a的值是多少?为什么在指针方面会有所不同? -
考虑到无效分配和其他问题,您的代码不是正确的minimal reproducible example,因为它甚至无法构建。始终测试您向我们展示的minimal reproducible example,以确保它复制了您提出的问题并且没有任何不相关的问题。
-
您是否介意edit 提出您的问题并提供一些详细信息您有什么问题,好吗? -- 在任何情况下,您都需要检查
realloc()的结果,但我不认为这是导致崩溃或您得到任何结果的原因。 -- 正如 Someprogrammerdude 已经说过的,将结构分配给指向结构的指针是错误的。将编译器的警告级别提高到最大并更正代码,直到不再输出诊断信息。您需要重新考虑要分配的内容。