我正在尝试使用数组指针实现堆栈。当堆栈已满时,它将扩展其原始大小的两倍。当堆栈中存储的元素数量是堆栈大小的一半时,它将缩小一半。推很好。问题是流行音乐。当我把testSize放在pop中时,程序崩溃了(见结巴行)。有谁能帮我找到修理它的方法吗?
#include <stdio.h>
#include "stack.h"
#include <stdlib.h>
double* initialize(int* top)
{
*top=0;
return (double*)malloc(sizeof(double)*2);
}
// add a new value to the top of the stack (if not full)
void push(double* stack, int* top, const double new_value, int *stack_size)
{
*(stack+*top)=new_value;
++*top;
testSize(stack,stack_size,top);
}
// remove (and return) the value at the top of the stack (if not empty)
double pop(double* stack, int* top,int* stack_size)
{
**//testSize(stack,stack_size,top);**
if(*top)
{
int temp=--*top;
double result= *(stack+temp);
**//testSize(stack,stack_size,top);**
return result;
}
printf("%d top \n",*top);
return 0;
}
void testSize(double *stack, int *stack_size, int * top) //size operation
{
if(*top==*stack_size) //see if it is full
{
stack=(double*)realloc(stack,(*stack_size)*sizeof(double)*2); //expand size reallocate memory
*stack_size=*stack_size*2;
}else if(*top<*stack_size/2)
{
//shrink
}
}
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
int main(int args, char* argv[])
{
double* my_stack = NULL;
int my_top = 0;
int stack_size=2; //initial dynamic array size
my_stack=initialize(&my_top); //initial size of 2
int p;
for(p=0;p<10;++p)
push(my_stack,&my_top,p+0.1,&stack_size);
pop(my_stack,&my_top,stack_size);
printf("%d elements total \nDynamic current stack size %d \n",my_top,stack_size); //summary
//print stack
int i;
for(i=my_top-1; i>=0; --i)
{
printf("%f \n", *(my_stack+i));
}
free(my_stack);
return 0;
}
最佳答案
pop()
函数将int*
作为第三个参数,但在下面的行中传递int
:
pop(my_stack, &my_top, stack_size);
应该是:
pop(my_stack, &my_top, &stack_size);
所以在
testSize()
中,当您试图取消引用这个非指针时,程序崩溃。关于c - 如何解决与C中动态数组指针/堆栈有关的崩溃?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21816771/