【问题标题】:While loop doesnt work?虽然循环不起作用?
【发布时间】:2018-05-13 14:50:48
【问题描述】:

几天前我们在课堂上写了这段代码,老师试图解释它,我们大多数人都不明白。我现在几乎完全理解它了,但是为什么第二个 while in main 不起作用?它应该在弹出之前输出一个名称。

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

typedef struct STK_S{
    char name[100];
    struct STK_S *next;
}STK;
int push(STK **ppS, STK *pD);
int pop(STK **ppS, STK *pD);

int main(){
    STK *pS, d;
    pS = NULL;
    while (1){
        printf_s("Ime ");
        gets_s(d.name, 100);
        if (d.name[0] == 0)
            break;
        push(&pS, &d);
    }
    while (pop(&pS, &d))
        printf_s("\n%s", d.name);
    return 0;
}

int push(STK **ppS, STK *pD){
    STK *pt;
    pt = (STK *)malloc(sizeof(STK));
    if (pt == NULL)
        return 0;
    *pt = *pD;
    pt->next = *ppS;
    *ppS = pt;
    return 1;
}

int pop(STK **ppS, STK *pD){
    STK *pt;
    if (*ppS == NULL){
        printf("Empty stack.\n");
        return NULL;
    }
    *pD = **ppS;
    pt = *ppS;
    *ppS = pt->next;
    free(pt);
    return 0;
}

【问题讨论】:

  • 在 pop() 结束时返回 1。
  • 是的,我复制了正确的代码,我知道这些返回值相同(有点)。多谢你们。现在可以使用了。
  • NULL 是 null-pointer 文字。您不想从返回 int 的函数中返回。
  • 顺便说一句,不需要像 C 而不是 C++ 那样从 malloc() 转换结果。

标签: c list while-loop stack


【解决方案1】:

pop 返回NULL0,它们都转换为false。所以循环不会运行一次。

【讨论】:

  • 是的,我将第二个返回值更改为 1,现在可以使用了,谢谢!但我想知道为什么它甚至可以工作?如果它释放了那个元素的内存,它是如何被打印出来的?
  • 可能是运气。释放后访问内存是未定义的行为;实际上,释放的内存往往会保留它的数据一段时间(直到它被重用),所以打印仍然会在那里找到它。
  • @JustSteve:它被复制并保存在这里:*pD = **ppS; 之前*ppS指向的内存被释放。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多