gpt4 book ai didi

c - 收到 SIGSEGV 错误。找不到负责的指针

转载 作者:行者123 更新时间:2023-11-30 16:16:04 24 4
gpt4 key购买 nike

我刚刚开始研究 C 中的链表,我似乎在打印部分遇到了无限循环,尝试修复仍然遇到相同问题的所有 Unresolved 问题。我已经尝试调试多次,但始终是 SIGSEGV 错误。我使用过 DEV C++ 和 GCC 4.9.2。

#include<stdio.h>
#include<stdlib.h>

typedef struct node {
int data;
struct node *next;
}node;

void print();
node *clist(int n);
node *head = NULL;

int main()
{
int n;
printf("Input the number of nodes for the Linked List.\n");
scanf("%d", &n);

clist(n);
print();

return 0;
}

void print()
{
node *show = NULL;
show = head;
while (show != NULL) {
printf("%d => ", show->data);
show = (show->next);
}

printf("NULL");

}

node *clist(int n)
{
node *temp = NULL;
node *p = NULL;
int i;

for (i = 0; i<n; i++)
{
temp = (node*)malloc(sizeof(node));

printf("Enter the element %d of the list", i + 1);
scanf("%d", &temp->data);

if (head == NULL)
{
head = temp;

}

else {
p = head;
while( p->next )
{
p = p->next;
}
p->next = temp; //UPDATE: SIGSSEGV ERROR HERE NOW
}
}
return head;
}

最佳答案

以下建议代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确检查并处理错误
  4. 始终缩进
  5. 自行清理
  6. 避免语句中的冗余,例如:if( head == NULL )
  7. 消除未使用的返回值
  8. 正确声明不带参数的函数原型(prototype)
  9. 为了便于阅读,使用适当的水平间距

现在,建议的代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct snode
{
int data;
struct snode *next;
} node;

// prototypes
void print( void );
void clist( int n );
void cleanup( void );

node *head = NULL;


int main( void )
{
int n;

printf( "Input the number of nodes for the Linked List.\n" );
if( scanf( "%d", &n ) != 1 )
{
fprintf( stderr, "scanf for number of data points failed\n" );
exit( EXIT_FAILURE );
}

clist( n );
print();
cleanup();
return 0; // << optional in modern C
}


void print()
{
node *show = head;

while( show )
{
printf( "%d => ", show->data );
show = show->next;
}

puts( "" );
}


void clist( int n )
{
node *temp = NULL;
node *p = NULL;

for( int i=0; i<n; i++ )
{
temp = malloc( sizeof( node ) );
if( !temp )
{
perror( "malloc failed" );
cleanup();
exit( EXIT_FAILURE );
}

// EDIT:
temp->next = NULL;
// end EDIT:

printf( "Enter the element %d of the list", i+1 );
if( scanf( "%d", &temp->data ) != 1 )
{
fprintf( stderr, "scanf for a data failed\n" );
cleanup();
exit( EXIT_FAILURE );
}

if( !head )
{ // list empty
head = temp;
}

else
{ // list already contains some nodes
p = head;

while( p->next )
{
p = p->next;
}
p->next = temp;
}
}
}


void cleanup()
{
node *temp = head;
node *current;

while( temp )
{
current = temp;
temp = temp->next;
free( current );
}
}

这是程序简单运行的输出:

Input the number of nodes for the Linked List.
2
Enter the element 1 of the list1
Enter the element 2 of the list2
1 => 2 =>

建议在输出中的节点数据值的用户输入之前放置一个空格

关于c - 收到 SIGSEGV 错误。找不到负责的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com