【问题标题】:copy const char* to string in c将 const char* 复制到 c 中的字符串
【发布时间】:2012-10-11 15:24:09
【问题描述】:

在 C [不是 C++] 中:

如何将const char* 复制到字符串(字符数组)中?

我有:

const char *d="/home/aemara/move/folder"
char tar[80] ;
int dl=strlen(d);
int x=0;
while (x<dl){tar[x]=d[x]; x++; }
printf("tar[80]: %s\n",tar);

打印出来:tar[80]: /home/aemara/move/folderøèB 问题是这种方式会在数组末尾添加垃圾[有时,并非总是] 我该如何解决?或者还有其他方法可以将const char* 复制到字符串中?

【问题讨论】:

  • @GregHewgill 他可能想学习如何复制两个字符串。可能是功课
  • @PrototypeStark:我当然理解练习用于学习的想法,但如果是这样,那么为什么允许 strlen() 呢?此外,除非明确指定,否则我不会假设随机限制。

标签: c string char constants


【解决方案1】:

strlen 返回不带空终止符的长度。您需要再复制一个字节。

【讨论】:

    【解决方案2】:

    复制后忘记在末尾添加“\0”字符。

    要解决这个问题,memset(tar,'\0',80);

    或者:

    if(d1 < 80){ //bad idea, don't use magic numbers
      while(x < d1){ tar[x] = d[x]; x++;}
      tar[x] = '\0';
    }
    printf..
    

    【讨论】:

      【解决方案3】:

      strlen 的返回值不包含 NULL 终止符。

      while 循环之后添加以下行

      tar[dl] = '\0';
      

      或者您可以在声明数组时将tar 初始化为零。

      char tar[80] = {0};
      

      现在你不需要在循环之后终止 NULL。

      【讨论】:

        【解决方案4】:

        这是你应该做的:

        const char *d="/home/aemara/move/folder";//Semi-colon was missing in your posted code
        char tar[80];
        memset(tar,0x00,80);//This always a best practice to memset any array before use
        int dl=strlen(d);//This returns length of the string in excluding the '\0' in the string
        int x=0;
        if(dl<79)// Check for possible overflow, 79th byte reserved=1 byte for '\0'
        while (x<dl){ tar[x]=d[x]; x++; }
        if(x<80) d[x]=0;//If not using memset have to use this, xth byte initialized to '\0'
        printf("\ntar[80]: %s\n",tar);
        

        【讨论】:

        • “这始终是在使用之前对任何数组进行 m​​emset 的最佳实践”。不,这不对。那是防御性编程,可能会简单地掩盖其他逻辑错误。虽然在某些情况下,第一步清除数组是合适的,但在大多数情况下应该是不必要的。
        • 评论是针对 OP 的问题和上下文的。我也同意你的 cmets。
        猜你喜欢
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        • 2022-01-10
        • 2015-11-21
        相关资源
        最近更新 更多