我想實現一個使用數組指針的堆棧。當堆棧滿時,它會擴展兩倍的原始大小。當堆棧中存儲的元素數量是堆棧的一半時,它會減少一半。推送工作正常。問題是流行。當我把testSize放入彈出窗口時,程序崩潰(請參閱廢棄的行)。任何人都可以幫我找到我解決它嗎?如何解決這個與C中的動態數組指針/堆棧有關的崩潰?
#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;
}
爲什麼標記爲C++?而且,你是否嘗試過使用調試器,比如gdb?並且,不要大小寫malloc –
使用調試器,在碰撞觀察變量附近走棧 – Drop