【问题标题】:Appending individual characters from string onto a char pointer将字符串中的单个字符附加到 char 指针上
【发布时间】:2015-01-04 06:42:26
【问题描述】:

我正在用 C 编写一个解析器,我有一些看起来像这样的代码:

char *consume_while(parser *self, int(*test)(char)) {
    char *result;
    while (eof(self) && (*test)(next_char(self))) {
         // append the return value from the function consumed_char(self)
         // onto the "result" string defined above.
    }
    return result;
}

但我对 C 的整个字符串操作方面有点陌生,所以我如何将从函数 consumed_char(self) 返回的字符附加到 result 字符指针?我见过有人使用strcat 函数,但这不起作用,因为它需要两个常量 char 指针,但我正在处理一个 char* 和一个 char。在java中它会是这样的:

result += consumed_char(self);

C 中的等价物是什么? 谢谢:)

【问题讨论】:

  • (*test)(next_char(self))改成test(next_char(self))会更容易阅读。
  • 为小费干杯! :)

标签: c string pointers dynamic-allocation


【解决方案1】:

在 C 中,字符串不作为一种类型存在,它们只是带有空终止字符的 char 数组。这意味着,假设您的缓冲区足够大并用零填充,它可以很简单:

result[(strlen(result)] = consumed_char(self);

如果没有,最好的办法是使用strcat 并更改consumed_self 函数以返回char *

话虽如此,在没有基本了解 C 风格字符串的情况下编写解析器,至少可以说是相当雄心勃勃的。

【讨论】:

  • 谢谢,目前正在按照这些思路实施,但我很快就要上大学了
  • 这里的重点是假设你的缓冲区足够大。这是崩溃的常见原因,也是 C++ 中字符串的(一个)原因之一。但我同意你的最后一句话:-)
  • 好吧,我知道 char* 是一个以空字符结尾的 '\0' 字符数组。我只是想要一个动态的并使用 malloc 的解决方案,也许我不清楚。
猜你喜欢
  • 2013-01-04
  • 2021-07-30
  • 1970-01-01
  • 2012-10-04
  • 1970-01-01
  • 2010-12-12
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多