c - realloc 不适用于指针,但没有它也可以。该怎么办?
问题描述
TRIP* ReadTravel(int* pnum_trips)
{
TRIP* tr = NULL;//initiallization for realloc
char stop = '0';
while (stop != STOP_INSERTING_TRIPS)
{
tr = (TRIP*)realloc(tr, (1+ *pnum_trips) * sizeof(TRIP));
tr[*pnum_trips] = ReadTrip();
(*pnum_trips)++;
printf("If you want to stop adding trips, type '%c'\n", STOP_INSERTING_TRIPS);
printf("if you want to continue adding trips, type any other key\n");
scanf(" %c", &stop);
}
return tr;
}
void main()
{
TRIP* trav;
int num_trips = 0;
int i;
trav = ReadTravel(num_trips);
PrintTravel(trav, num_trips);
}
TRIP ReadTrip()
{
TRIP tr;
printf("Enter the city you START your trip in: ");
scanf("%s", tr.starting_city);
printf("Enter the city you END your trip in: ");
scanf("%s", tr.destination_city);
printf("Enter the starting date of the trip:\n");
tr.trip_start = ReadDate();
printf("Enter the arrival date of the trip:\n");
tr.arrival_date = ReadDate();
printf("Enter the price of the trip: ");
scanf("%lf", &tr.trip_price);
return tr;
}
TRIP 是代码中的一个结构,假设它有效,因为这不是我在这里的原因。与“realloc”一致,似乎有问题,但我不明白是什么。当我删除“*pnum_trips”时,它似乎工作正常,但我不明白“*pnum_trips”有什么问题。请帮助编辑:我添加了 main() 和 ReadTrip()
解决方案
推荐阅读
- c - 如何找到每个大小为 n 的 m 个数组的最长公共子数组?
- c++ - Visual Studio C++ 2019。如何将 wstring 转换为 WCHAR *
- computer-vision - 如何使用 Mediapipe 包中的姿势估计找到人脸位置(人脸的边界框)?可能吗?
- python - Python:Tkinter 绑定(“<
>") 只工作一次 - javascript - 无法通过检查域来运行功能
- .net - 如何将 Version/PackageVersion 参数传递给 DotNet Core CLi
- java - 如何以编程方式格式化 Java 代码片段
- python - 如何应用 LSTM 预测停车可用性
- c# - 在控制台应用程序 c# 中显示 PrintDialog
- java - 如何将项目列表添加到 ImageView