首页 > 解决方案 > 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()

标签: crealloc

解决方案


推荐阅读