增加结构尺寸W / Realloc(ERROR第二次增加)

时间:2015-01-06 14:05:51

标签: c dynamic structure realloc

我是一名初学者,正在尝试为大学课程做一个项目,需要使用动态结构。 我的问题: 我使用realloc来增加我的结构的大小,它第一次工作,但不是第二次。我用来接收新增加的struture的辅助指针似乎第二次得到NULL值。

到目前为止,这是我的代码:

我尝试增加结构的功能:

TList *addToQueue (TList *plist, int *counter, char departure)
{
    TList *auxiliary;
    auxiliary = NULL;

    auxiliary = realloc(plist,(*counter+1)*sizeof(TList));

    if (auxiliary == NULL)
    {
        printf("Insufficient Memory");
        cleanstdin();
    }
    else
    {
        plist = auxiliary;
        plist[*counter].departure = departure;

        do{
        printf("\nPoint of Arrival: ");
        plist[*counter].arrival = checkMenuOption(OPTIONSLOC);
        }while(plist[*counter].arrival == '\0');

        printf("\nNumber of passengers:");
        plist[*counter].numberOfPassengers = readIntenger(MIN_SEATS, MAX_SEATS);

        (*counter) ++;

        printf("\nTicket Purchased successfully");
        cleanstdin();

    }
    return plist;
}

我如何宣称主要:

TList *addToQueue (TList *plist, int *counter, char departure);

我如何打电话给主:

char离开;

            departure = sellTicketsMenu ();

            switch (departure)
            {
            case 'A':
            {
                ListA = addToQueue (ListA, &counterA, departure);
                cleanstdin();
            }
            break;
            case 'B':
            {
                ListB = addToQueue (ListB, &counterB, departure);
                cleanstdin();
            }
            break;
            case 'C':
            {
                ListC = addToQueue (ListC, &counterC, departure);
                cleanstdin();
            }
            break;
            }

其他说明:readintenger - 从键盘读取整数的基本功能 cleanstdin - 基本清晰的替代疗法 checkmenuoption - 检查菜单选项的功能 counter - 用于帮助构造索引的计数器

如果您需要了解或帮助我,请告诉我。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

  1. 最好发布 here 而非非现场

  2. 非现场代码(在已删除的答案中发布)通过reallloc()通过addToQueue()调用一个已经准备好免费的指针。

     case 'C':
       ...
       free(ListA);
       switch (optionMTI) {
         case 'A': {
           ...
           ListA = addToQueue (ListA, &counterA, departure);
    
  3. 问题是重复使用free'd指针 如果代码要在free()之后重新使用指针,请务必将其指定给NULL

                // Fixed code  
                free(ListA);
                ListA = NULL;  // add
                ...
                ListA = addToQueue (ListA, &counterA, departure);
    

答案 1 :(得分:0)

由于缺少源代码而无法确认的唯一可能解释是,在第一次调用之前,传递的参数counter未初始化或list未设置为NULL

您必须将其初始化为0,典型的for循环看起来像

int counter;
int i;
int numberOfStructs;
TList *list;

counter = 0; /* <--- this is the important part */
numberOfStructs = SOME_NUMBER_MAY_BE_FROM_INPUT;
list = NULL;
for (i = 0 ; i < numberOfStructs ; ++i)
    list = addToQueue (list, &counter, departure);

在您的情况下,您可以尝试

int counterA = 0;
int counterB = 0;
int counterC = 0;

counter*变量定义。