void * memcpy ( void * destination, const void * source, size_t num );
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
- int arr2[10] = { 0 };
- memcpy(arr2, arr1, 20);
- int i = 0;
- for (i = 0; i < 10; i++)
- {
- printf("%d ", arr2[i]);
- }
- return 0;
- }
我的模拟实现:
void * memmove ( void * destination, const void * source, size_t num );
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
- memmove(arr1+2, arr1, 20);
- int i = 0;
- for (i = 0; i < 10; i++)
- {
- printf("%d ", arr2[i]);
- }
- return 0;
- }
模拟实现:
- void * memmove ( void * dst, const void * src, size_t count)
- {
- void * ret = dst;
- if (dst <= src || (char *)dst >= ((char *)src + count)) {
-
- while (count--) {
- *(char *)dst = *(char *)src;
- dst = (char *)dst + 1;
- src = (char *)src + 1;
- }
- }
- else {
-
- dst = (char *)dst + count - 1;
- src = (char *)src + count - 1;
- while (count--) {
- *(char *)dst = *(char *)src;
- dst = (char *)dst - 1;
- src = (char *)src - 1;
- }
- }
- return(ret);
- }
void * memset ( void * ptr, int value, size_t num );
- #include
- #include
- int main ()
- {
- char str[] = "hello world";
- memset (str,'x',6);
- printf(str);
- return 0;
- }
结果:
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
memcmp函数是比较两个内存块的内容是否相同
ptr1和ptr2是两个要比较的内存块首地址,num是要比较的大小,单位是字节。
如果相同,则返回0;
如果不相同,则返回值大于或小于0,表示第一个不同字节的差值。
如:ptr1='abcd'
ptr2='accd'
则返回b-a的值
使用:
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char buffer1[] = "DWgaOtP12df0";
- char buffer2[] = "DWGAOTP12DF0";
- int n;
- n = memcmp(buffer1, buffer2, sizeof(buffer1));
- if (n > 0)
- printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
- else if (n < 0)
- printf("'%s' is less than '%s'.\n", buffer1, buffer2);
- else
- printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
- return 0;
- }