I'm learning C in a restricted OS (xv6) that only has a subset of C. I'm trying split a single string into an array of strings.
To do that, I've constructed an array of pointers to strings lines
. My expectation is that lines will end up looking like this:
lines = { "abc", "def", "ghi" }
When I try to access lines by index (e.g. lines[0]) I'm getting null
. I'm stumped why I'm getting null and have tried several things. I'm pretty sure I'm missing something very obvious.
Note: Not looking for working code, as I would like to continue building this myself, but would appreciate some guidance on why I'm getting this result.
#define STDIN 0
#define STDOUT 1
static void readline(){
char buff[] = "abc\ndef\nghi";
int i,j;
char current[20];
char *lines[20];
int counter = -1;
int lines_counter = -1;
for(i = 0; i < 14; i++) {
if(buff[i] == '\n' || buff[i] == '\0'){
lines_counter++;
for(j = 0; j < 4; j++) {
lines[lines_counter][j] = current[j];
}
counter = -1;
} else {
current[++counter] = buff[i];
}
}
printf(STDOUT, "%s", lines[0]); // expected "aaa", instead output is(null)
}
int main(int argc, char *argv[]) {
readline();
exit();
}
I would advise just looking at the source code of
strtok
and try expanding any standard library calls.strchr
is just a search for a char in a string andstrcspn
just counts the number of characters beforestrchr
returns.