When I pass a plain string to a function that returns single lines from that string and advances it to the next line, the function does not advance the string but overwrites it with the first line instead and loops endlessly.
char *consume_next_line(char *text_ptr)
{
char *cursor = text_ptr;
if (!*cursor)
return NULL;
char *line = cursor;
while (*cursor && (*cursor != '\n'))
++cursor;
char *end = cursor;
if (*cursor) {
++end;
if (*(cursor-1) == '\r')
--cursor;
*cursor = '\0';
}
text_ptr = end;
return line;
}
int main(void)
{
char *file_data = read_entire_file("main.c");
int i = 0;
char *line;
while (line = consume_next_line(file_data)) {
++i;
printf("%d: %s\n", i, line);
}
return 0;
}
1: int main(void)
2: int main(void)
3: int main(void)
...
When I pass the string as a pointer instead, it works fine (consume_next_line()
and read_entire_file()
are defined in a different file, this is an example).
char *consume_next_line(char **text_ptr)
{
char *cursor = *text_ptr;
if (!*cursor)
return NULL;
char *line = cursor;
while (*cursor && (*cursor != '\n'))
++cursor;
char *end = cursor;
if (*cursor) {
++end;
if (*(cursor-1) == '\r')
--cursor;
*cursor = '\0';
}
*text_ptr = end;
return line;
}
int main(void)
{
char *file_data = read_entire_file("main.c");
int i = 0;
char *line;
while (line = consume_next_line(file_data)) {
++i;
printf("%d: %s\n", i, line);
}
return 0;
}
1: int main(void)
2: {
3: char *file_data = read_entire_file("main.c");
4:
5: int i = 0;
6: char *line;
7:
8: while (line = consume_next_line(file_data)) {
9: ++i;
10: printf("%d: %s\n", i, line);
11: }
12:
13: return 0;
14: }
I tested it with both GCC and MSVC and the result is the same. Why is that? Shouldn't both snippets work the same?