我正在尝试构建一个程序来创建自动机状态(他的符号 + 下一个状态)并显示状态
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct State
{
int state;
char symb;
int newState;
struct State *next;
}State;
State *head,*neww,*p;
void Add()
{
int i,j;
printf("How many transitions in your automata\n");
scanf("%d",&j);
for(i=0;i<j;i++)
{
if(neww!=NULL)
{
neww = (struct State *)malloc(sizeof (struct State));
printf("State number:");
scanf("%d",&neww->state);
printf("With which symbole to the next state:");
scanf(" %c",&neww->symb);
printf("To which state :");
scanf("%d",&neww->newState);
neww->next=NULL;
if(head==NULL)
{
head=neww;
}
else{
p = head;
while(p->next !=NULL)
{
p=p->next;
}
p->next = neww;
}
}
}
}
void Display()
{
p=head;
while(p != NULL)
{
printf("State : %d to state : %d with symbole : %c \n\n",p->state,p->newState,p->symb);
p = p->next;
}
printf("END\n");
}
int main(void)
{
head = NULL;
Add();
Display();
return 0;
}
你能帮我弄清楚为什么它在第一次 printf 后停止工作吗?
EDIT1:现在它在将 scanf("%d",j) 更改为 &j 后在第二个 printf 之后停止
EDIT2:在更正所有 scanfs 后它工作正常!
EDIT3:我在代码中添加了更正,现在我在显示中有一个循环,它不停地显示状态我猜这是一个链接问题
EDIT4:显示中的循环是由于未为其他状态分配空间;我会将更正添加到代码中
感谢帮助
最佳答案
您的代码中几乎没有错误。您还没有阅读转换、状态编号和其他变量。只需在整个程序中更正 scanf
的语法,其他一切都会正常工作。在scanf
中的变量前添加一个&
。
关于c - 链接列表(在 C 中)为什么这不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33185784/