繁体   English   中英

malloc 和免费堆栈在 C

[英]malloc and free on a Stack in C

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

#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 指针作为非 static 指针而不是 *newElem 指针,但这也没有用。

它应该是一个链表。 我们的教授刚刚给了我们这个练习,甚至从未以任何方式或形式提及链表。非常感谢,它现在可以工作了!

我将推送 function 更改为:

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

newElem->myPoint = pushPoint;

newElem->next = stacktop;

stacktop = newElem;

和弹出 function 到:

POINT b = stacktop->myPoint;

free(stacktop);

stacktop = stacktop->next;

return b;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM