c - 双向链接中的用户输入

标签 c clang

我正在尝试构建一个程序,该程序接受用户输入,然后反转输入。输出显示原始字符串和反转字符串。该程序编译但给我以下错误“0ÿÿÿ;原始链接列表段错误(核心转储)”

这是我的代码:

 struct node
 {
 int info;
 struct node *next;
 struct node *prev;
 }node;
 void reverse(struct node **head_1)
 {
 struct node *temp = NULL;
 struct node *current = *head_1;
 while (current !=  NULL)
  {
       temp = current->prev;
       current->prev = current->next;
       current->next = temp;
       current = current->prev;
     }     
      if(temp != NULL )
       *head_1 = temp->prev;
   }    
void push(struct node** head_1, int new_data)
{
    struct node* new_node =
    (struct node*) malloc(sizeof(struct node));

     new_node->info  = new_data;
     new_node->prev = NULL;
    new_node->next = (*head_1);   
    if((*head_1) !=  NULL)
      (*head_1)->prev = new_node ;   
      (*head_1)    = new_node;
 }
void printList(struct node *node)
{
while(node!=NULL)
    {
    printf("%s ", node->info);
    node = node->next;
    }
        }

 int main()
 {
struct node* head = NULL;
char str[300], ch;
int i;
printf("enter ");
    while((ch=getchar())!='\n');
{
str[i++]=ch;
str[i]='0';
i=0;
}
    while (str[i]!='\0')
{ 
putchar(str[i++]);
push(&head, ch);
}
    printf("\n Original ");
    printList(head);
    reverse(&head);
    printf("\n Reversed ");
    printList(head);          

     getchar();
     }

最佳答案

您正在使用未初始化的变量i访问str

int i;//Unitialized variable
printf("enter ");
    while((ch=getchar())!='\n');
{
str[i++]=ch;//This will acess memory at address str+random value from i  

更改int i; to int i = 0;

还有printf("%s ", node->info);node->info 以来不正确是整数,不是字符串。应该是类似 printf("%d ", node->info);

我发现了其他问题,但我怀疑它是否是最终版本。

    while((ch=getchar())!='\n');//why ;? this will lead to all chars to be skipped and only \n will be passed to the loop body
{
str[i++]=ch;
str[i]='0';//it should be '\0' instead of '0', and there is no sense to set it on each iteration
i=0;//This will reset i on each iteration overwriting previous char
}

关于c - 双向链接中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16136832/

相关文章:

c - 常量结构内的函数指针

c - 我的分号怎么了? (gcc 预处理器)

visual-studio - 如何在 Visual Studio 中使用 LibTooling/Clang?

objective-c - clang 编译错误(对 objc_autoreleasepoolpush 的 undefined reference )

objective-c - 为什么 gcc 或 clang 不能正确地@encode SIMD 矢量类型?

c - 处理 awk 命令时如何将 'system()' 调用转换为 'fork() + execl()' ?

c - 如何从字符串中获取数值(将其转换为 int)?

c - 如何将数组的一部分从二维数组复制到 C 中的另一个数组

c - 为什么我不能在设置 F_SEAL_WRITE 后创建只读的共享映射?

python - 试图掌握 clang\cindex.py 中的 CachedPropery