我想將一個字符串傳入函數,並返回鏈表,每個節點包含字符串。 因此,在主要功能,你可以看到如何將字符串列表存儲到節點中?
list = newTB("hello\ngood\nworld");
然後,newTB應該返回列表,這就好比..
[hello]-> [good]-> [world]->null
必須有我的newTB功能錯誤,因爲賽格故障不斷出來..
請人幫助我..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "textbuffer.h"
#define MAX_TEXT 256
typedef struct textbuffer *TB;
struct textbuffer {
char *texts;
int count; // counts how many nodes in the list
TB next;
};
void printBuffer(TB tb){
TB curr = tb;
int i=0;
while(curr != NULL){
printf("POS %d : %s\n", i++, curr->texts);
curr = curr->next;
}
}
int linesTB(TB tb) {
return (tb->count);
}
TB newTB (char text[]){
TB newText = malloc(sizeof(struct textbuffer));
char *cpy = (char *)malloc(MAX_TEXT * sizeof(char));
strcpy(cpy,text);
newText->count = 0;
newText->next = NULL;
int i = 0;
int j = 0;
while(cpy[i] != '\0') {
if(j == 0) {
newText->texts = (char *)malloc(MAX_TEXT * sizeof(char));
}
if(cpy[i] == '\n') {
newText->count++;
newText->next = malloc(sizeof(struct textbuffer));
newText = newText->next;
j = 0;
} else {
newText->texts[j++] = cpy[i++];
}
}
return newText;
}
void releaseTB (TB tb) {
TB head = tb;
TB tmp;
while(head != NULL) {
tmp = head;
head = head->next;
free(tmp->texts);
free(tmp);
}
}
int main(int argc, char * argv[]) {
TB list = NULL;
list = newTB("hello\ngood bye\nworld\n");
printf("**THERE ARE %d LINES IN TEXTBUFFER**\n", linesTB(list));
printBuffer(list);
printf("%s\n",dumpTB(list));
releaseTB(list);
return 0;
}
它在哪裏段錯? – woolstar
我想,你在這裏想念你的頭:'newText = newText-> next;'不是嗎? –
並且您只爲頭節點初始化newText-> count。 –