如何使用后方指针正确使用下标(结构化队列程序)

时间:2018-10-09 16:34:45

标签: queue structure

我目前正在尝试为结构化方法设计一种入队方法。在此程序中,我在引用下面程序数组中的下标时遇到了麻烦。我必须使用* rear + 1才能正确引用它吗?还是我必须使用另一种语法才能正确引用下一个元素。

 bool Enqueque(int** queue, int* front, int* rear, int* nElements, int* capacity, 
                  int userInput)
    {   

        //if there is no more space in the Queue
        if( *nElements == *capacity )
        {
            //update the capacity
            *capacity = *nElements * 2;

            //asked OS for more memory
            int* growQueue = (int*)malloc( (*capacity) * sizeof(int) );

            //error checking
            if(growQueue == NULL)
                return false;

            //take all the elements from the original queue and put into the bigger queue  
            for(int i = 0; i<*nElements; i++)
                growQueue[i] = (*queue)[i];
            free(*queue);
            *queue = growQueue;

            (*queue)[*nElements] = userInput;
            nElements++;

        }

        //if there is space in the queue
        else if(*nElements+1 > *capacity)
        {
            //if queue is empty
             if(front == NULL)
            {
                //front and rear are both pointers to the same element
                front = queue[0];
                rear = queue[0];

                (*queue)[0] = userInput;
                *nElements++;
                return true;
            }

             else if(*nElements >= 1)
             {
                 //move the userInput into the next available spot behind the 
                 //element after rear. plus four because int takes 4 bytes
                (*queue)[ (*rear)+1 ] = userInput;


                //The array subscript below is not working correctly
                rear = (*queue)[ rear+1 ];
                 return true;
             }
        }    
    }

0 个答案:

没有答案