0

I know strncpy(s1, s2, n) copies n elements of s2 into s1, but that only fills it from the beginning of s1. For example

s1[10] = "Teacher"
s2[20] = "Assisstant"
strncpy(s1, s2, 2) would yield s1[10] = "As", correct?

Now what if I want s1 to contain "TeacherAs"? How would I do that? Is strncpy the appropriate thing to use in this case?

Johnny
  • 41
  • 2
  • 6

5 Answers5

2

You can use strcat() to concatenate strings, however you don't want all of the source string copied in this case, so you need to use something like:

size_t len = strlen(s1);
strncpy(s1 + len - 1, s2, 2);
s2[len + 2] = '\0';

(Add terminating nul; thanks @FatalError).

Which is pretty horrible and you need to worry about the amount of space remaining in the destination array. Please note that if s1 is empty that code will break!

There is strncat() (manpage) under some systems, which is much simpler to use:

strncat(s1, s2, 2);
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
0

Use strcat.

Make sure your string you're appending to is big enough to hold both strings. In your case it isn't.

From the link above:
char * strcat ( char * destination, const char * source );

Concatenate strings Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

destination and source shall not overlap.

0

In order to achieve what you need you have to use strlcat (but beware! it is considered insecure)

strlcat(s1, s2, sizeof(s1));

This will concatenate to s1, part of the s2 string, until the size of s1 is reached (this avoids memory overflow)

then you'll get into s1 the string TeacherAs + a NUL char to terminate it

Community
  • 1
  • 1
Davide Berra
  • 6,387
  • 2
  • 29
  • 50
0

you need to make sure that you have enough memory is allocated for the resulting string

s1[10]

is not enough space to fit 'TeacherAs'.

from there, you'll want to do something like

//make sure s1 is big enough to hold s1+s2
s1[40]="Teacher";
s2[20]="Assistant";

//how many chars from second string you want to append
int offset = 2;
//allocate a temp buffer 
char subbuff[20];
//copy n chars to buffer
memcpy( subbuff, s2, offset );
//null terminate buff
subbuff[offset+1]='\0';

//do the actual cat
strcat(s1,subbuff);
75inchpianist
  • 4,112
  • 1
  • 21
  • 39
0

I'd suggest using snprintf(), like:

size_t len = strlen(s1);
snprintf(s1 + len, sizeof(s1) - len, "%.2s", s2);

snprintf() will always nul terminate and won't overrun your buffer. Plus, it's standard as of C99. As a note, this assumes that s1 is an array declared in the current scope so that sizeof works, otherwise you'll need to provide the size.

FatalError
  • 52,695
  • 14
  • 99
  • 116