Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the memory functions in C language

2025-04-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces what are the memory functions in C language, which can be used for reference. I hope you can learn a lot after reading this article.

Memory function 1. Copy memcpy,memmove

Void * memcpy (void * destination, const void * source, size_t num)

Dest replicates num bytes of data in src.

Simulation and implementation of memcpy

Void * my_memcpy (void * dst, const void * src, size_t count) {void * ret = dst; while (count--) {* (char *) dst = * (char *) src; dst = (char *) dst + 1; src = (char *) src + 1;} return (ret);}

What happens if dst and src point to the same array?

Int main () {int arr1 [10] = {1 int arr1 [10] = {1 int I = 0; / / expected results 1 2 1 2 3 4 7 8 9 0 my_memcpy (arr1+2, arr1, 16); for (int I = 0; I

< 10; i++) { printf("%d ", arr1[i]); }} 实际为 1 2 1 2 1 2 7 8 9 0 因为到5 6 的时候3 4被改成了1 2 ,5 6也就被改成1 2。 也就是说被复制的元素在复制前被改变了,导致复制结果失败。 如果是这样指向同一个数组呢? int main(){ int arr1[10] = { 1,2,3,4,5,6,7,8,9,0 }; my_memcpy(arr1, arr1+2, 16); for (int i = 0; i < 10; i++) { printf("%d ", arr1[i]); }} 复制结果没有问题。 对于这种情况,c语言有一个更强大的函数memmove. void * memmove( void * destination, const void * source, size_t num ); 与memcpy的功能一样,但是memmove可以指向同一块空间。 模拟实现memmove **void* my_memmove(void* dest, void* src, size_t num){ char* ret = dest; //如果指向同一块空间 判断地址大小,避免数据在被复制前被改变 if ( (char*)dest-(char*)src< 0){ while (num) { *((char*)dest)++ = *((char*)src)++; num--; } } else { while(num--){ *((char*)dest+num) = *((char*)src+num); } } return ret;}2.比较 memcmp int memcmp ( const void * ptr1, const void * ptr2, size_t num ); 从ptr1和ptr2的位置开始比较num个字节,当两个字节数据不同时就会返回。 ptr1>

Ptr2 return value > 0

Ptr1=ptr2 return value = 0

Ptr1

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report