hey guys , one question please , can someone tell me what exactly the role of the function " memcpy()" in C language
it copies the value of one variable to another, especially useful working with pointers.
lets say you created a heap allocated char array:
char* arr = malloc(sizeof(char) * 10);
now when you need to assign a value into it, you can't just do:
*arr = "test";
because *arr refers to the first element's memory address which requires a char, not a whole string. you also can't do:
arr = "test";
because this will override the heap allocated data's pointer. how? "test" is a const char*, and when you assign it to arr, you are effectively replacing the malloc created pointer with const char*. which causes memory leak. plus, you shouldn't be assigning const char* to a char* anyway.
Instead, you have two options. 1:
memcpy(arr, "test", sizeof("test" /* or just 5 */));
or 2:
strcpy(arr, "test");
Both these options are valid.
It is also great to use when you are copying the values of one array to another.
Assume that you have an array of 25 integers and you are creating a new array of 25 integers. you want to copy the original 25 integers into the new array. The long way is to use a for loop and copy the values one by one into the new array. memcpy gives you the same result without needing to manually iterate and copy. it is a one line of code