我试图通过流的内容循环来动态生成列表中的节点,给出了我读取的每一行的内容。我有如下定义的结构:无法指定字符指针循环中的结构
struct info {
char *mystring;
char *file;
int line_no;
struct info *next;
};
我用这个循环通过流迭代:
while(1) {
char t [KMAX];
char* file;
char* line_no;
char* text;
if (fgets(t, KMAX, file_pipe) != NULL) {
file = strtok (t, delimiter);
line_no = strtok(NULL, delimiter);
int line = atoi(line_no);
text = strtok(NULL, delimiter);
add(&head, text, line, file);
}
我知道变量正确传递给我的附加功能,因为我打印出来每次我都可以验证它。但是,当我尝试打印列表时出现问题。它只是打印文本和文件名的最后一行,但整数值相应地改变。我的猜测是它与数组被删除有关,并且每次都在同一块内存中被重新创建,所以指针每次都会改变。
我不确定正确的方法是去解决这个问题。我是否以某种方式修改我的while循环并以不同的方式使用char指针,或者我应该改变结构以保存变量,而不是仅仅使用指针?我会很感激任何反馈!
编辑:添加更多的代码
void add(struct info **x, char * text, int line_no, char * file) {
struct info* current = *x;
struct info* newInfo;
newInfo = malloc(sizeof(struct info));
(*newInfo).next = NULL;
(*newInfo).grepstring = text;
(*newInfo).line_no = line_no;
(*newInfo).file = file;
if (current == NULL) { //indicates the head is null, special case
*x = newInfo;
} else {
//get to the end of the list
while ((*current).next != NULL) {
current = (*current).next;
}
//apends node to the end of the list
(*current).next = newInfo;
}
}
错误必须在添加或打印列表中的代码。你可以请他们发表。 – 2012-02-03 02:36:21
为了能够确定问题的原因,我们需要查看您提及的打印电话的确切位置。 也是迂腐,我会建议在每次调用后检查strtok返回null,这将意味着字符串t null终止字符已被发现 – Lefteris 2012-02-03 02:40:14
那么,它是什么? '结构信息'或'结构说'? – 2012-02-03 02:56:25