C将字符串解析为没有任何lib函数的字符数组

标签 c arrays string pointers char

我正在尝试做的是解析字符串,其中包含到字符数组的空格。所以如果输入是“ab cd ef”,我希望我的数组是 array[0]==ab,array[1]==cd,array[2]==ef。我希望这说明了一切。但是问题是我不能使用任何库函数。没有 string.h,没有 fget,只有 scanf 和 printf。这是我的代码片段:

char word[25] = "";
char *words[25];

for (int i = 0; i <= find_length(input); i++){
    if(input[i] == ' ' || i == find_length(input)){
        words[position] = word;
        printf("%s%d ",words[position], position);
        position++;
        counter = 0;
        word[0] = '\0';
    }
    else{
        word[counter] = input[i];
        counter++;
    }
}

position = 0;

while(counter < 5){
    printf("%s%d ",words[position], position);
    counter++;
}

首先,我将字符串解析为单个单词,然后尝试将它们放入数组中。我希望我的逻辑是正确的。所以问题是,第一个 printf(for 循环中的一个)打印正确的值及其位置。然而第二个 printf(这只是为了确保字符串被正确解析)只打印 0。 因此,例如输入“ab cd ef”给出:

ab0 cd1 ef2 0 0 0 0 0

我怀疑问题是我没有向数组的数组添加值,只是分配指针。而且由于我转储了“单词”,所以它们没有任何意义。如果那是正确的,我如何分配值而不是指针?

当然,这个假设可能是错误的,如果是这样,您能指出我的错误以及如何改正吗?谢谢。

PS:我知道我应该 strcpy value of string not = it,但正如我所说,除了 scanf 和 printf(find_length 是我自己的函数)我不能使用任何库函数

最佳答案

我不太同意@harper 的回答,因为主要问题如下,因为 OP 几乎自己想通了:

I suspect that problem is that I am not adding values to the array of arrays, just assigning pointers. And since I dump "word", they point to nothing. If that is correct, how do I assign values instead of pointers?

此代码将使 words[0] 指向与字符数组 word 关联的内存块。然后 words[1] 将指向同一个 block 。然后是words[3]等等..

最后,char* 数组 words[] 中的所有元素都将指向 char 数组 word[],其中将包含一个 '\0' 作为其第一个元素,看到 OP 重复执行此 word[0] = '\0';

所以我提出的修复方法,除了最后已经提到的关于 while 循环的内容之外,是为每个子字符串分配内存,然后使用简单的 for 复制 word[] 的内容 循环。

所以这样:

for (int i = 0; i <= find_length(input); i++){
    if(input[i] == ' ' || i == find_length(input)){
        words[position] = word;
        printf("%s%d ",words[position], position);
        position++;
        counter = 0;
        word[0] = '\0';
    }

会变成这样:

for (int i = 0; i <= find_length(input); i++) {
    if(input[i] == ' ' || i == find_length(input)) {
    words[position] = malloc(sizeof(char) * (counter + 1));
        for (int j = 0; j < counter; j++)
            words[position][j] = word[j];
        words[position][counter] = '\0';
        printf("%s%d ", words[position], position);
        position++;
        counter = 0;
        word[0] = '\0';
    }

关于C将字符串解析为没有任何lib函数的字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41064486/

相关文章:

c - 如何扫描带有空格的字符串并打印它们 C

c - 为什么这个程序会出现段错误?

php - 处理对象数组时如何避免循环中的array_merge

c++ - 我可以像 C++ 中的数组一样迭代类成员吗?

javascript - 在 JavaScript 中从另一个对象创建对象

从 C 中的字符串数组创建字符串

c - C 中 if(function() == TRUE) 的任何原因

c - 如何使用格式化字符串攻击

c - 这个 C 代码有定义的行为吗?

c++ - 如何将 std::string 转换为 QString