c - 链接列表(在 C 中)为什么这不起作用

标签 c linked-list

我正在尝试构建一个程序来创建自动机状态(他的符号 + 下一个状态)并显示状态

这是我的代码:

#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/

相关文章:

c - 如何正确打印链表成员

c - 如何在链表的开头插入节点?

c - 如何解决错误 "assignment makes integer from pointer without a cast"?

c - 找出某个值存储在内存的哪一部分?

c - 在 BST 中查找字符串

c - 如何删除代码中 undefined reference ?

algorithm - 仅使用 3 个指针查找链表中间三分之一的元素?

Ruby 链表实现 #remove!阻止无效

c - 我对 "The C Programming Language"第二版(1991)有什么期待。例子里面解释

c - 解析 C 字符串