-1

For example, I have this string:

ABABcct

Can I copy

ABc
begin index = 2, end index = 4 

...from that string?

Is there any specific built-in function that can do this?

I know strncpy() can copy a number of characters of a string starting from the beginning of the string onto another. But I don't think it can do what I have just described. As far as I know, its "begin index" is limited to 0.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Soha Farhin Pine
  • 313
  • 6
  • 16

3 Answers3

2

Actually you can use the function strncpy() with a pointer to anywhere in your string, not only a pointer to its beginning.

Example:

char *src = strdup("ABABcct");
char *dest;

strncpy(dest, src + 2, 3) // Copies 3 characters from your pointer src + 2 to your pointer dest

If you run this code, dest will contain ABc.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
0

With strncpy

#include <stdio.h>
#include <string.h>
int main(void)
{
    char p[10],s[10]="abcdefgh";
    strncpy(p,s+2,3);
    puts(p);
    return 0;
}

I know strncpy() ... As far as I know, its "begin index" (as I call it) is limited to 0.

You knew it wrong. It's not about begin index or anything - simply you need to pass relevant char* in src and target which is being done here.
To add further clarification - most standard library functions which you are talking about never put a constraint of passing the pointer to the 0-th index. It doesn't matter which index you send - you can send 100th or 50th doesn't matter as long it follows the things expected by function (null termination etc).

The code posted here is for illustration purpose - didn't include the necessary checks needed to use str*cpy functions.

user2736738
  • 30,591
  • 5
  • 42
  • 56
0

While in your case the standard copy functions would eventually work, their use is not allowed when the source and the destination are overlapped, in which case you'll experience an UB.

For such issue the standard C library provide the function memmove designed to handle overlapped areas. It works as using an intermediate buffer to solve any overlapping problem.

see also Meaning of overlapping when using memcpy

Frankie_C
  • 4,764
  • 1
  • 13
  • 30