[英]Array of pointers to strings printing null
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.我在一个只有 C 的子集的受限操作系统 (xv6) 中学习 C。我正在尝试将单个字符串拆分为一个字符串数组。
To do that, I've constructed an array of pointers to strings lines
.为此,我构建了一个指向字符串
lines
的指针数组。 My expectation is that lines will end up looking like this: lines = { "abc", "def", "ghi" }
我的期望是线条最终看起来像这样:
lines = { "abc", "def", "ghi" }
When I try to access lines by index (eg lines[0]) I'm getting null
.当我尝试按索引访问行(例如行 [0])时,我得到了
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.我建议只查看
strtok
的源代码并尝试扩展任何标准库调用。 strchr
is just a search for a char in a string and strcspn
just counts the number of characters before strchr
returns. strchr
只是在字符串中搜索字符,而strcspn
只是计算strchr
返回之前的字符数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.