【问题标题】:Why \001 is added when strcat is invoked为什么调用 strcat 时会添加 \001
【发布时间】:2013-05-26 01:56:11
【问题描述】:

看下面的代码:

char chs[100] = "Hello World";
char token[100];
int pos = -1;
while((current = chs[++pos]) != '"'){
      strcat(token, &current);
}

但输出是:

H\001e\001l\001l\001o\001 \001W\001o\001r\001l\001d

有什么想法吗?

【问题讨论】:

  • @mbratch 输出应该是 Hello World
  • @Foredoomed 您想去掉字符串文字周围的引号?引号实际上并不是字符串的一部分!也许您应该从阅读book 开始。
  • @Foredoomed,但这只是应该是从chstoken 的字符串副本吗?如果是这样,那么这就是strcpy 的用途。你只需做strcpy(token, chs); 就可以了。不需要循环。还是有其他目的?如果你想使用strcat,它要求两个字符串参数都以零结尾。所以你至少需要设置token[0] = '\0' 在循环之前开始,正如我所提到的。

标签: c strcat


【解决方案1】:

strcat() 需要一个以空字符结尾的字符串作为输入。因此 strcat(token, &current) 将从当前地址开始读取并继续读取,直到找到空值。碰巧的是,您在 current 之后的内存中是“\001”,因此每次您执行 strcat 时,它都会将所有内容复制到令牌中。

你应该做 char current[] = "\0\0" 然后用 current[0] = chs[++pos] 赋值。这样, current 将始终具有该 null 终止。

【讨论】:

    【解决方案2】:

    你有未定义的行为

    由于您的current 未声明,我猜它是一些未初始化的字符。您的 current = chs[++pos]) 设置字符,但 strcat(token, &current); 希望 current 成为字符串,因此在变量 current 之后保存了一些垃圾。请发布更多示例代码以供进一步分析

    顺便说一句 '"' 看起来不对 C

    【讨论】:

      【解决方案3】:

      进行最小的更改,这是您的代码的工作版本:

      #include <string.h>
      #include <stdio.h>
      
      int main()
      {
          char current[2] = { 0x0, 0x0 }; // Will be null terminated
          char chs[100] = "Hello World";
          char token[100] ;
          int pos = -1;  // Destination of strcat must also be null terminated
      
          token[0] = '\0' ;
      
          // String literals does not actually have " in memory they end in \0
          while((current[0] = chs[++pos]) != '\0')
          {
                  strcat(token, &current[0]); // Take the address of the first char in current                      
          }   
      
          printf("%s\n", token ) ;
      
          return 0 ;
      }
      

      strcat 期望源和目标都是以空字符结尾的字符串。在您的情况下,它看起来像 current 刚刚结束了在内存中的 \001 后跟一个空终止符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        • 2015-12-01
        • 2015-03-08
        • 1970-01-01
        • 1970-01-01
        • 2023-02-13
        相关资源
        最近更新 更多