私は文字列の順番でリンクリストにノードを挿入しようとしています。私は、私がプログラムを実行するときにセグメンテーションフォルトに達するので、私が信じているポインターに問題があります。ノードには、文字列のchar配列と数値を表すintという2つのデータフィールドがあります。リストは名前だけでソートする必要があります。Cで順番にlinkedListに挿入
後typedef struct node {
char *name;
int num;
struct node *next;
} Node;
Node *head = NULL;
int insertInOrder(char *newName, int favNum) {
Node *current = head;
Node *newNode;
Node *tempNode;
int nodeIn = 0;
if (head == NULL) {
head = malloc(sizeof(Node));
if(head == NULL){
fprintf(stderr, "ERROR: Out of memory\n");
return 1;
}
head->name = newName;
head->num = favNum;
head->next = NULL;
} else {
while (current != NULL) {
if (strcmp(newName, current->name) == 0) {
fprintf(stderr, "ERROR: Name already exists in the list\n");
return 1;
}
if (strcmp(newName, current->name) < 0) {
tempNode = current->next;
newNode = malloc(sizeof(Node));
if(newNode == NULL){
fprintf(stderr, "ERROR: Out of memory\n");
return 1;
}
newNode->name = newName;
newNode->num = favNum;
newNode->next = tempNode;
current->next = newNode;
nodeIn = 1;
}
current = current->next;
}
if(nodeIn == 0){
newNode = malloc(sizeof(Node));
if(newNode == NULL){
fprintf(stderr, "ERROR: Out of memory\n");
return 1;
}
newNode->name = newName;
newNode->num = favNum;
current->next = newNode;
newNode->next = NULL;
}
}
return 0;
}
あなたは 'valgrind'を実行しようとしましたが、どの行でセグメンテーションフォルトが発生しましたか? – galfisher
'insertInOrder'の呼び出しを表示できますか?私は問題がそこにあると思う。 – Michas
データ文字列が現在のノードのデータ文字列よりも小さい場合は、nextnodeの前ではなく、currentnodeの前に挿入し、新しいノードを前のノードからリンクする必要があります。 –