-1

I'm basically just taking a string and appending / concatting with another string. The first run through produces the desired results, but the 2nd, 3rd and so on results seem to be doubling the src string. Combining things with jQuery is super simple, not sure whats going on here in C. Should I be using memset? or 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;
}

I'm expecting to see results such as

Michelle becomes Mic.. This works, however if my name structure has 4 names and they were all Michelle the results are...

Mic..
Mic....
Mic......
Mic........
ikegami
  • 367,544
  • 15
  • 269
  • 518
user3622460
  • 1,231
  • 5
  • 23
  • 42
  • 2
    The code you posted has a syntax error. Which means that it is not the exact code you tried to run. – Mike Nakis Jun 02 '17 at 20:33
  • Hmm compiles and runs for me. I typed it out exactly the way I have it, it does look like I missed a ) though. I'll edit the missing bracket. – user3622460 Jun 02 '17 at 20:39
  • 1
    You want like [this](http://ideone.com/AHz2Oe). Also Use `snprintf` insterd of `sprintf`. – BLUEPIXY Jun 02 '17 at 20:48

1 Answers1

1

You didn't heed the following warning:

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.

Replace

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

with

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

or just

yourName[3] = '.';
yourName[4] = '.';
yourName[5] = '\0';
ikegami
  • 367,544
  • 15
  • 269
  • 518