为什么这个基本的C程序会导致无限循环?
问题描述:
我的任务是建立一个“代表堆栈”的基本链表。所以数据只能按照后进先出的原则进行访问。我必须在该“堆栈”上应用某些功能。 我的代码编译得很好,但执行时,它只是无限打印1个。我不知道这是如何,因为我真的只使用一个while循环。 有谁知道我的问题是什么?也许我可以在将来避免这样的错误。感谢您的任何帮助。并提前道歉,我是一个初学者!为什么这个基本的C程序会导致无限循环?
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack {
struct Stack *next;
int data;
} Stack;
Stack* push(Stack*head, int d) { //add a datapoint to the top of the stack
Stack *temp;
temp=malloc(sizeof(Stack));
temp->data=d;
temp->next=head;
return temp;
}
Stack* pop(Stack*head) { //read the top data point, and delete it
Stack* newHead=head->next;
printf("%i", head->data);
free(head);
return newHead;
}
int peek(Stack*head) { // return the top datapoint, without delete
return head->data;
}
void isempty(Stack*head) {
if (head==NULL) {
printf("Stack empty");
}
printf("Stack has data");
}
void print(Stack*head) { //print complete Stack
Stack* cursor;
cursor=head;
while (cursor!=NULL) {
printf("%i", cursor->data);
}
}
int main(int argc, const char * argv[]) {
Stack* head;
head=malloc(sizeof(Stack));
head=NULL;
head=push(head, 4);
head=push(head, 2);
head=push(head, 1);
printf("%i", peek(head));
print(head);
head=pop(head);
print(head);
isempty(head);
head=pop(head);
head=pop(head);
isempty(head);
return 0;
}
答
你不会在功能上print
增加cursor
:
while (cursor!=NULL) {
printf("%i", cursor->data);
}
的代码也在这里出现内存泄漏:
head=malloc(sizeof(Stack));
head=NULL;
答
你有功能print
一个无限循环。您需要在循环内更新cursor
,否则它将永远循环。这是我会怎么做:
void print(Stack*head) { //print complete Stack
Stack* cursor;
for (cursor = head; cursor != NULL; cursor = cursor->next) {
printf("%i", cursor->data);
}
}
答
在此代码:
while (cursor!=NULL) {
printf("%i", cursor->data);
}
你是不是改变光标。因此,将其更改为
for (cursor = head; cursor!=NULL; cursor = cursor->next) {
printf("%i", cursor->data);
}
答
您的循环在功能上print
步骤一个前:
void print(Stack*head)
{
Stack* cursor = head;
while (cursor != NULL) //
{
printf("%i", cursor->data);
cursor = cursor->next; // step one forward
}
}
而且存在内存泄漏。您可变head
分配内存,但你是正确后设置为NULL
:
Stack* head;
// head=malloc(sizeof(Stack)); // delete this
head=NULL;
答
while循环有一个问题:
while (cursor!=NULL) {
printf("%i", cursor->data);
cursor = cursor->next; // you forgot this line
}
没有这一行,光标永远不会改变。
'head = malloc(sizeof(Stack)); head = NULL;'这两个语句实现了什么? –
移除'head = malloc(sizeof(Stack));'在main行 - 这不是必需的 –