C 新手,但我正在尝试编写此链接列表程序,但我不断收到分段错误:11. 我认为我已经将其缩小到仅在链接列表创建中的问题 - 我将其标记为问题区。当我将此部分注释掉时,不会发生段错误。
我一直在讨论纸上发生的事情,但我不明白为什么它不起作用。也许我只是误解了指针或 malloc 的使用,因为我没有经验。
该程序应使用的示例文本文件:
>984932:39284 mus musculus okodvcxvmkw2e2p \n
ATCTCAATCGCACTATCTAGCATGTCGTATGCTTGCATGTCGTAGTCGT\n
ATGCTATGCTTACTCTATTTACGGCGCATCGTGATCGTAGGAGCGAGCT\n
>984932:39284 mus huumoros okodvcxvmkw2e2p \n
ATCTCAATCGCACTATCTAGCATGTCGTATGCTTGCATGTCGTAGTCGT\n
ATGCTATGCTTACTCTATTTACGGCGCATCGTGATCGTAGGAGCGAGCT\n
>984932:39284 mus pisces okodvcxvmkw2e2p \n
ATCTCAATCGCACTATCTAGCATGTCGTATGCTTGCATGTCGTAGTCGT\n
ATGCTATGCTTACTCTATTTACGGCGCATCGTGATCGTAGGAGCGAGCT\n
我正在尝试做的事情:创建一个链表,其中每个节点都是上面文本的一个块。也就是说,每个节点都包含以'>'开头的头部,以及作为所有ACTG的序列数据。在上面的示例文本文件中,除了列表中的头/尾节点之外,还有 3 个节点。
我是如何尝试的(问题部分): Char 被扫描。如果 char 是 '>',那么我们知道我们在头部,并且我们将所有后续字符读入新节点的头部字段,直到我们到达换行符。此时,我们知道我们将读取序列数据。继续这样做,直到我们到达另一个“>”,当我们这样做时,重复。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int list_header_size = 200;
int list_data_size = 2000;
struct list{
char *header;
char *data;
struct list *next;
struct list *prev;
};
//append char onto a string
void append(char *s, char c){
int len = strlen(s);
s[len] = c;
s[len + 1] = '\0';
}
int create_list(char *filename){
FILE *fp = fopen(filename, "r");
if(fp == NULL){
printf("File could not be opened. Exiting..");
exit(1);
}
//setup head - doesn't hold a char
struct list *head = malloc(sizeof(struct list));
head->next = NULL;
head->header = NULL;
head->data = NULL;
head->prev = NULL;
//setup tail - doesn't hold a char
struct list *tail = malloc(sizeof(struct list));
tail->next = NULL;
tail->header = NULL;
tail->data = NULL;
tail->prev = NULL;
/***scan the .fasta file, populate list***/
//char holder
char c;
int list_size = 0;
int i = 1;
//pull single char from file until end of file is reached
do{
c = getc(fp);
//******PROBLEM IS IN THIS SECTION********//
//if header text is found
if(c == '>'){
//create a node
struct list *temp = malloc(sizeof(struct list));
//first case to setup head
if(i == 1){
head->next = temp;
temp->prev = head;
i = 0;
}
tail->next = temp;
tail->prev = temp;
//create space for header/sequence data in the new node
temp->header = (char*) malloc(sizeof(list_header_size));
temp->data = (char*) malloc(sizeof(list_sequence_size));
//add current char to header
append(temp->header, c);
c = getc(fp);
//put file's header data into node's header data
while(c != '\n'){
append(temp->header, c);
c = getc(fp);
}
//put file's sequence data into node's sequence data
while(c != '>' && c != EOF){
append(temp->data, c);
}
}
//*******END OF PROBLEM SECTION********//
}while(c != EOF);
/***end of scanning .fasta file and creating linked list***/
return 1;
}
int main(int argc, char * argv[]){
char *filename = (char*) malloc(80);
//check options
int i;
for(i = 1; i < argc; i++){
if(argv[i][0] == '-'){
switch(argv[i][1]){
default:;
}
}else{
//arg is filename
filename = argv[i];
}
}
create_list(filename);
return 1;
}