我正在创建三个函数,这些函数使我能够以不同方式使用指针格式的指针插入链表。问题是我在这些功能之一中遇到段错误,并且gdb出于某种原因没有告诉我它们在哪里。关于它们的位置有什么建议吗?
// This is the function where I can insert to the front:
void insertAtHead( List *list, int val )
{
Node **link = &( list->head );
Node *n = (Node *)malloc(sizeof(Node));
n->value = val;
n->next = *link;
list->length++;
}
//This is the function where I can insert at the end.
void insertAtTail( List *list, int val )
{
Node **link = &( list->head );
Node *n = (Node *)malloc(sizeof(Node));
Node *temp;
n->value = val; // Link the data part
n->next = NULL;
temp = *link;
while(temp->next != NULL)
temp = temp->next;
temp->next = n; // Link address part
list->length++;
}
//This function lets me insert the value by finding the largest value and putting the given value before it.
void insertSorted( List *list, int val )
{
Node **link = &( list->head );
Node *n = (Node *)malloc(sizeof(Node));
Node *temp;
n->value = val; // Link the data part
n->next = NULL;
temp = *link;
while(temp->next != NULL || val < temp->value)
temp = temp->next;
temp->next = n; // Link address part
list->length++;
}
// Lastly, the main function:
int main( int argc, char *argv[] )
{
FILE *fp;
if ( argc != 2 || ( fp = fopen( argv[ 1 ], "r" ) ) == NULL ) {
printf( "Can't open file: %s\n", argv[ 1 ] );
exit( EXIT_FAILURE );
}
{
List list = { NULL, 0 };
int val;
while ( fscanf( fp, "%d", &val ) == 1 )
insertAtHead( &list, val );
printList( &list );
freeList( &list );
}
fseek( fp, SEEK_SET, 0 );
{
List list = { NULL, 0 };
int val;
while ( fscanf( fp, "%d", &val ) == 1 )
insertAtTail( &list, val );
printList( &list );
freeList( &list );
}
fseek( fp, SEEK_SET, 0 );
{
List list = { NULL, 0 };
int val;
while ( fscanf( fp, "%d", &val ) == 1 )
insertSorted( &list, val );
printList( &list );
freeList( &list );
}
fclose( fp );
return EXIT_SUCCESS;
}
我知道的主要功能和小功能的其余部分都是正确的,但问题似乎出在这三个功能之一。感谢您的帮助!