c - 指向打印 null 的字符串的指针数组
问题描述
我在一个只有 C 子集的受限操作系统 (xv6) 中学习 C。我正在尝试将单个字符串拆分为一个字符串数组。
为此,我构建了一个指向 strings 的指针数组lines
。我的期望是线条最终看起来像这样:
lines = { "abc", "def", "ghi" }
当我尝试按索引访问行(例如行 [0])时,我得到null
. 我很难过为什么我会变得空,并尝试了几件事。我很确定我错过了一些非常明显的东西。
注意:不是在寻找工作代码,因为我想自己继续构建它,但希望能得到一些关于我为什么会得到这个结果的指导。
#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();
}
解决方案
我建议只查看源代码strtok
并尝试扩展任何标准库调用。strchr
只是在字符串中搜索一个字符,并在返回strcspn
之前计算字符数。strchr
推荐阅读
- caching - 我应该在 Redis 中设置“常量”结果缓存的过期时间吗?
- bash - 使用 grep 保留重复的行
- python - Python BeautifulSoup 网页抓取 Tripadvisor 查看评论
- docker - VS Code 远程容器无法获取本地颁发者证书
- reactjs - 更改上下文时如何立即更新错误值
- c++ - C++中数组指针的Malloc空间
- sparql - 如何清除 fuseki 中未使用的空间
- r - tree.cv 回归的变量重要性图
- python - 如何在python中打印变量“new_text”
- apache2 - WSL2 Apache2 反向代理仅排除子域的根