2014-02-16 45 views
0

我想實現一個使用數組指針的堆棧。當堆棧滿時,它會擴展兩倍的原始大小。當堆棧中存儲的元素數量是堆棧的一半時,它會減少一半。推送工作正常。問題是流行。當我把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; 
} 
+0

爲什麼標記爲C++?而且,你是否嘗試過使用調試器,比如gdb?並且,不要大小寫malloc –

+0

使用調試器,在碰撞觀察變量附近走棧 – Drop

回答

1

pop()功能需要一個int*作爲第三個參數,但你在下面的行傳遞一個int

pop(my_stack, &my_top, stack_size); 

應該是:

pop(my_stack, &my_top, &stack_size); 

所以在testSize()當您嘗試去引用程序崩潰的這個非指針。

2

這條線:

pop(my_stack,&my_top,stack_size); 

應該

pop(my_stack,&my_top,&stack_size); /* take address of stack_size with '&' */ 

我建議你用-Wall選項編譯並查找警告,然後消滅他們。這不僅可以改善您的編碼風格,還可以幫助您快速找到這類事物。