저는 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;
}
"stringdb_add"함수는 새 노드가 배치 된 위치를 반환해야하지만 함수를 테스트 할 때 (00111111 ....) 만 얻습니다.
목록이 제대로 링크되지 않았기 때문일 수 있습니다.
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
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다