【发布时间】:2016-01-04 15:27:09
【问题描述】:
我今天在编写一个在 C 中使用 static char* 的函数时遇到了问题。
让我解释一下:我的函数在我们发送给她的缓冲区中找到'\n',如果'\n' 后面有任何文本,它必须将此文本存储到名为rest 的静态变量中。事实是它存储了它,但 rest 的内容在函数的两次调用之间没有保留。而且我不明白为什么会发生这种情况,尽管它被声明为静态变量。
到目前为止,这是我的功能:
(return (1) 表示该函数没有找到\n 和\0,return (0) 表示该函数找到了\n,(return -1)表示该函数找到了EOF)
static int end_line(char *buf, char **line)
{
static char *rest;
char *tmp;
rest = NULL;
tmp = ft_strnew(ft_strlen(buf));
tmp = buf;
printf("REST BEGINNING : %s\n", rest);
if (rest != NULL)
{
tmp = ft_strnew(ft_strlen(rest) + ft_strlen(buf));
tmp = ft_strcat(rest, buf);
}
if (!ft_strchr(tmp, '\n') && ft_strchr(tmp, '\0') == NULL)
{
rest = tmp;
return (1);
}
else
{
ft_putstr("OK\n");
*line = ft_strsub(tmp, 0, (ft_strlen(tmp) - ft_strlen(ft_strchr(tmp, '\n'))));
rest = ft_strchr(tmp, '\n') + 1;
if (ft_strlen(ft_strchr(tmp, '\0')) == 0)
return (-1);
return (0);
}
}
【问题讨论】:
-
test_static除了声明之外还有什么用处? -
抱歉,test_static 是我在发布之前忘记删除的测试^^ 将 rest 初始化为 NULL 有什么问题?
-
真的应该给出更简洁的代码示例,更简洁地写问题。
-
另外还有一个问题。
-
问题不是初始化,而是赋值。