- 函数名称:expandStack
- 输入:指向堆栈类型的指针 (Stack*)
- 输出:无
- 函数操作:函数展开堆栈
void expandStack(Stack* stack){
//Check the stack and the array are allocated
if (stack == NULL ||stack->content == NULL)
{
return;
}
//Allocating a new sized array (*2 from the previous)
Element* expandedStack = (Element*)malloc(2 * (stack->size) * sizeof(Element));
//Case malloc failed
if (expandedStack == NULL)
{
printf("Error! Malloc has failed in file 'stack.c', 'expandStack' function\n");
return;
}
//Updating size field
stack->size *= 2;
//Copy values from the previous array to the new array allocated
for (int i = 0; i <= stack->topIndex; i++)
{
expandedStack[i].c = stack->content[i].c;
}
//Free old array
free(stack->content);
//Point to the new array in the heap
stack->content = expandedStack;
}
在这一行:expandStack[i].c = stack->content[i].c; 我收到一个“绿色警告”,说:“c6386 缓冲区在写入 'expandedStack' 时溢出:可写大小为 '2 * (stack->size) * sizeof(Element)' 字节,但可能会写入 '2' 字节。
问题是代码工作正常,它可以编译。