2014-01-25 2 views
3

저는 C를 처음 사용하고 프로그래밍에 익숙해졌으며 링크 된 목록을 살펴보기 시작했습니다.새 노드를 C의 연결된 목록에 연결하는 데 문제가 있습니다.

static struct post { 
    char * str; 
    struct post * next; 
} 
head = {0, NULL}; 


int stringdb_add(const char * str) { 
    int pos = 0; 
    struct post * new_input = (struct post *) malloc(sizeof(struct post)); 
    new_input - > str = (char *) malloc(strlen(str) + 1); 

    if (head.next == NULL) { 
     strcpy(new_input - > str, str); 
     new_input - > next = NULL; 
     head.next = new_input; 
    } else { 
     while (head.next - > next) { 
      ++pos; 
      head.next = head.next - > next; 
     } 
     strcpy(new_input - > str, str); 
     new_input - > next = NULL; 
     head.next - > next = new_input; 
    } 

    return pos; 
} 

기능은 새로운 노드에 배치 된 위치를 반환하도록되어 있지만이 기능을 테스트 할 때 난 단지 (... 00111111)를 얻을 "stringdb_add".

목록이 제대로 링크되지 않기 때문일 수 있습니다.

+0

당신은 시도를 위해 +1을 얻습니다. 그러나 들여 쓰기를 위해 -1을 얻을 수 있습니다 - 그것을 정렬하십시오. –

답변

3
while (head.next->next) { 
    ++pos; 
    head.next = head.next->next;   
} 

당신은 영구적으로 당신이 원하는 확실하지 않은 head.next 변경됩니다. 당신은 아마 뭔가를 원하는 :

struct post *p = &head; 
while (p->next->next) 
/* ... */ 

Nitpick : strcpy(new_input->str, str)if 전에, 한 장소에있을 수 있습니다.

+0

좋아요, 이제 totaly가 작동했습니다. 전체 p 포인터가 모든 것을 더 쉽게 만들었습니다. 귀하의 도움과 정말 qucik 대답 주셔서 감사합니다! :) – Adlon

관련 문제