Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - memcpy()

C library function - memcpy()

C Standard Library - <string.h> C Standard Library -

Description

C library function **void *memcpy(void str1, const void str2, size_t n) Copies str2 Copy n bytes from the source memory area to the destination memory area. str1.

Declaration

Here is the declaration of the memcpy() function.



void *memcpy(void *str1, const void *str2, size_t n)

Parameters

Return Value

This function returns a pointer to the destination memory area str1.

Example

The following example demonstrates the use of the memcpy() function.

Example

// Copy the string into the array dest

#include

<

stdio.h

#include

<

string.h

int

main

(

)

{

const

char

src

[

50

]

=

"

http://www.runoob.com

"

;

char

dest

[

50

]

;

memcpy

(

dest

,

src

,

strlen

(

src

)

1

)

;

printf

(

"

dest = %s

\

n

"

,

dest

)

;

return

(

0

)

;

}

Let's compile and run the above program, which will produce the following result:

dest = http://www.runoob.com

Copy 6 consecutive characters starting from the 11th character in s into d:

Example

#include

<

stdio.h

#include

<

string.h

int

main

(

)

{

char

s

=

"

http://www.runoob.com

"

;

char

d

[

20

]

;

memcpy

(

d

,

s

11

,

6

)

;

// Copy starting from the 11th character (r), 6 consecutive characters (runoob)

// Or memcpy(d, s+11sizeof(char), 6sizeof(char));

d

[

6

]

='\

0

';

printf

(

"

%s

"

,

d

)

;

return

0

;

}

Let's compile and run the above program, which will produce the following result:



runoob

Overwrite part of the original data:

Example

#include

<

stdio.h

#include

<

string.h

int

main

(

void

)

{

char

src

[

]

=

"

"

;

char

dest

[

]

=

"

abcdefg

"

;

printf

(

"

Before using memcpy: %s

\

n

"

,

dest

)

;

memcpy

(

dest

,

src

,

strlen

(

src

)

)

;

printf

(

"

After using memcpy: %s

\

n

"

,

dest

)

;

return

0

;

}

Let's compile and run the above program, which will produce the following result:



使用 memcpy 前: abcdefg

使用 memcpy 后: ***defg

C Standard Library - <string.h> C Standard Library -