对于我制作队列程序的结构化方法,当涉及到指针时,我在语法和数组索引方面遇到了一些问题。我已经标记了我遇到问题的行。这些都是不正确转换的问题还是语法不正确的问题?
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
//These two lines are giving warnings
//QueueLibrary.c:42:19: warning: assignment makes pointer from //integer without a cast [-Wint-conversion]
// front = (*queue)[0];
^
//QueueLibrary.c:43:18: warning: assignment makes pointer from integer without a //cast [-Wint-conversion]
//rear = (*queue)[0];
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.
//QueueLibrary.c:54:24: warning: cast from pointer to integer of different size //[-Wpointer-to-int-cast]
(*queue)[ (int)rear+1 ] = userInput;
(*queue)[ rear+1 ] = userInput;
//Array subscript is not an integer
rear = (*queue)[ rear+1 ];
return true;
}
}
}
最佳答案
您必须记住,使用array[index]
对数组进行索引相当于操作*(array + index)
。那么让我们看看您当前正在做什么以及为什么它是错误的。
你有变量int **queue
,它是一个指向int的指针。您想要提取前面并将其放入变量 int *front
中。您当前的方法是:
int *front = (*queue)[0];
并使用顶部产量的等价进行翻译:
int *front = *((*queue) + 0)
第一个(*queue)
取消引用queue
并产生一个int *
。然后将 0
添加到 int *
中,生成相同的值,然后取消引用它。取消引用 int *
会产生什么结果?
提示:您不应直接使用 foo = bar
将 int *foo
分配给 int bar
.
继续讨论其他问题,数组下标必须是整数。查看 int * back
的类型应该可以清楚为什么执行 array[rear]
会发出警告。
如果int *rear
应该指向队列的尾部,为什么不直接使用它作为指针,而不是尝试用它来索引队列呢? :)
关于c - 以结构化方法实现队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52680528/