【发布时间】:2016-12-28 11:36:33
【问题描述】:
我是结构的新手,我试图实现一个堆栈以及将数据推入堆栈并打印它们的操作。但是,我遇到了一些问题,请您帮我解决一下吗?
我使用了教程点提供的编译器,其中代码编译成功,但输出包含分段错误,我认为它存在于“PushNode”或“PrintStackData”中。
当我输出堆栈中的节点数(使用计数器)时,这个数字比正确的多一个,比如我输入了 5 个数据,但它打印出 6 个。
非常感谢!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//Define data node
typedef struct Node{
int data; //Data of data node in Stack
struct Node *Next; // Pointer pointing to next data node or null
}NODE;
//Define head node for stack
typedef struct StackHead{
int Counter;
NODE *Top;
}STACKHEAD;
// function to create a blank stack
void CreateStack(STACKHEAD *Head){
Head= (STACKHEAD*)malloc(sizeof(STACKHEAD));
Head->Counter=0;
Head->Top = NULL;
};
//Function to push a data node in stack
void PushNode(STACKHEAD *Head){
NODE *pNew=(NODE*)malloc(sizeof(NODE)); //Must allocate memory to initialise it otherwise segmentation error.
printf("Enter value for new data Node: ");
scanf("%d",&(pNew->data)); //Assign input to data of new node
if(Head->Top==NULL){
pNew->Next=NULL;
}
else{
pNew->Next=Head->Top;
}
Head->Top=pNew;
Head->Counter++;
};
//Function to print out each data node in the Stack
void PrintStackData(STACKHEAD *Head){
STACKHEAD *Position=(STACKHEAD*)malloc(sizeof(STACKHEAD));
//Position->Top=Head->Top;
Position = Head;
printf("The data in the Stack is: ");
while(Position->Top!=NULL){
printf("%d, ",Position->Top->data);
Position->Top= Position->Top->Next;
}
}
int main()
{
int numOfData; // Number of data that users want to insert into the stack
STACKHEAD *Head; //Declare and initialise a new Stack Head
CreateStack(Head); // Initialise the Stack
printf("How many data do you want to insert to the Stack?");
scanf("%d", &numOfData);
for(int i=0;i<numOfData;i++){
PushNode(Head);
}
printf("The data value of the top Node is %d\n", Head->Top->data);
PrintStackData(Head); //print out each data node in Stack using function.
printf("\nThe number of data in the Stack is: %d\t", Head->Counter);
printf("\nThe data value of the top Node is %d\t", Head->Top->data);
getchar();
}
【问题讨论】:
-
搜索并阅读关于在 c 中模拟传递引用。或者如何从函数中返回值。
-
“请调试我的代码”问题不在主题范围内/不允许。
-
你从未初始化过
Head。在CreateStack函数内分配给Head不会修改调用者的变量。 -
CreateStack应该返回分配的结构,而不是将其作为参数。 -
顺便说一下,您的
PrintStackData函数包含内存泄漏。 并且在您重写堆栈时出现了一个非常糟糕的逻辑错误(并导致更多的内存泄漏)。
标签: c data-structures stack