我的字符串连接每次都将其结果加倍,为什么?

My string concatination is doubling its result each time, why?

我基本上只是获取一个字符串并附加/连接另一个字符串。第一个 运行 通过产生所需的结果,但第二个、第三个等等结果似乎是 src 字符串的两倍。将东西与 jQuery 结合起来非常简单,不确定 C 中发生了什么。我应该使用 memset 吗?还是 calloc?

#include <stdio.h>
#include <string.h>

int main(void) {
  const char* name = "Michelle";
  char *ptr;
  char dest[30];
  char yourName[30];
  char dots[] = "..";
  int i;

  for (i=0;i<4;i++)
  {
    if (strlen(name) > 5)
    {
      sprintf(yourName, "%s", name);
      strncpy(dest, yourName, 3);
      ptr = strcat(dest, dots);
      sprintf(yourName, "%s", ptr);
      printf("%s\n", yourName);
    }
  }

  return 0;
}

我期待看到

这样的结果

米歇尔成为麦克.. 这行得通,但是如果我的名字结构有 4 个名字并且都是 Michelle,那么结果是...

Mic..
Mic....
Mic......
Mic........

您没有注意以下警告:

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

替换

ptr = strncpy(dest, yourName, 3);
strcat(dest, dots);
sprintf(yourName, "%s", ptr);

ptr = strncpy(dest, yourName, 3);
dest[3] = '[=11=]';
strcat(dest, dots);
sprintf(yourName, "%s", ptr);

或者只是

yourName[3] = '.';
yourName[4] = '.';
yourName[5] = '[=12=]';