I wrote a simple c program that only take the first two characters of one word and take the last three characters of the second word. I use strncpy to only copy the first 2 letter of name1 to name, and concatenate with the last three characters from name2.

However, when I run it. output will somehow like

Ediacy //correct

acy  //wrong

Ed?
acy  //wrong

Edk
   acy //wrong

Edv
   acy //wrong

// code sample
#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[100];

    char name1[] = "Edison";
    char *name2 = "Tracy";

    strncpy(name, name1, 2); // instead of get Ed, it tried to append one extra char behind it.
    strcat(name, name2+2);

    printf("%s\n", name);

    return 0; 
}

I will really appreciate if anyone help me to figure it out why it acts like this and how I can correct it?

有帮助吗?

解决方案

strncpy doesn't add a nul-terminator if the size is too small.

Try this:

strncpy(name, name1, 2);
name[2] = '\0';
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top