首页 > 解决方案 > 指向打印 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();
}

标签: cxv6

解决方案


我建议只查看源代码strtok并尝试扩展任何标准库调用。strchr只是在字符串中搜索一个字符,并在返回strcspn之前计算字符数。strchr


推荐阅读