在C中的堆栈上执行malloc和free

ajsxfq5m  于 2022-12-11  发布在  其他
关注(0)|答案(1)|浏览(161)

我正在尝试编写一个代码,动态地将一个点的坐标写入堆栈,并打印(和释放)它们:

#include <stdio.h>
#include <stdlib.h>

struct point{
    float x;
    float y;
    float z;
}; typedef struct point POINT;

struct stackPoint{
POINT myPoint;
struct stackPoint *next;
}; typedef struct stackPoint STACKPOINT;

static STACKPOINT *stacktop = NULL;

void printStackElement(POINT aPoint){
printf(" x:%f \t y:%f \t z:%f\n", aPoint.x, aPoint.y, aPoint.z );
}

void push(POINT pushPoint){
STACKPOINT *newElem = malloc(sizeof(STACKPOINT));
stacktop = stacktop +1;
newElem->myPoint = pushPoint;
stacktop = newElem;
}

POINT pop(){
    POINT b = stacktop->myPoint;
    free(stacktop);
    stacktop = stacktop -1;
    return b;
}

int isEmpty(){
    if(stacktop == NULL){
        return 1;
    }
    return 0;
}



POINT readPoint(){
    POINT a;
    printf("Please enter your x-Coordinate: ");
    scanf(" %f", &a.x);
    printf("Please enter your y-Coordinate: ");
    scanf(" %f", &a.y);
    printf("Please enter your z-Coordinate: ");
    scanf(" %f", &a.z);
    return a;
}


int main(){
    char quit = 0;
    while(quit !=1 ){
        printf("\n\n enter 'p' to enter another Point or 'q' to quit: " );
        scanf(" %s", &quit);
        switch(quit){
            case 'p':
                push(readPoint());
                break;
            
            case 'q':
                quit = 1;
                break;

            default:
                break;
        }
    }
    while(isEmpty() == 0){
        printStackElement(pop());
    }
}

它打印最后一个条目,但在打印倒数第二个条目之前,只会出现一条错误消息,即“正在释放的指针未分配”。
我试着在没有free()命令的情况下运行它,但是它只打印第一行和0的无穷多行
我还尝试使用 *stackTop指针作为非静态指针,而不是 *newElem指针,但也不起作用。

juud5qan

juud5qan1#

它应该是一个链表。我们的教授只是给了我们这个练习,甚至从来没有以任何方式或形式提到过链表。。非常感谢,它现在起作用了!
我将推送功能更改为:

STACKPOINT *newElem = malloc(sizeof(STACKPOINT));

newElem->myPoint = pushPoint;

newElem->next = stacktop;

stacktop = newElem;

和pop函数,以便:

POINT b = stacktop->myPoint;

free(stacktop);

stacktop = stacktop->next;

return b;

相关问题