memmove() in C
×


memmove() in C

60

 In C programming, "memmove" is a standard library function defined in <string.h>.

 It efficiently moves a specified number of bytes from one memory location to another, even if the source and destination memory regions overlap.

 This makes it suitable for scenarios where data needs to be shifted within the same buffer.

Syntax of "memmove" in C:

#include<string.h>
void *memmove(void *dest, const void *src, size_t n);

Parameters:

 dest: Pointer to the destination memory area where the data will be moved.

 src: Pointer to the source memory area from which the data will be copied.

 n: Number of bytes to be moved.


Return Value:

 Returns a pointer to the destination memory area (dest).


Implementation:

 The "memmove" function ensures correct copying of data, even if the source and destination memory areas overlap.

 It achieves this by first copying the data to a temporary buffer and then moving it to the destination.

 This method ensures that the original data remains intact, irrespective of any overlap between the source and destination memory areas.

 memmove is the same as memcpy except that memmove works even if the objects overlap.


Examples:

1Moving Array Elements:

// program for moving array in C
#include<stdio.h> 
#include<string.h> 

int main() {
    char str[] = "Hello, World!";
    memmove(str + 7, str, 6);
    printf("%s\n", str);
    return 0;
}	

Output:

Hello, Hello,

2Moving Structures:

// program for moving structures
#include<stdio.h> 
#include<string.h> 

struct Person {
    char name[20];
    int age;
};

int main() {
    struct Person person1 = {"John", 30};
    struct Person person2 = {"Doe", 40};
    memmove(&person1, &person2, sizeof(struct Person));
    printf("Name: %s, Age: %d\n", person1.name, person1.age);
    return 0;
}	

Output:

Name: Doe, Age: 40

3Moving Integer Array:

// program for moving integer array 
#include<stdio.h> 
#include<string.h> 

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    memmove(arr + 2, arr, 3 * sizeof(int));
    for (int A = 0; A < 7; A++) {
        printf("%d ", arr[A]);
    }
    printf("\n");
    return 0;
}	

Output:

1 2 1 2 3 32765 0 

4Moving Strings with Overlapping Regions:

// program for Moving Strings with Overlapping Regions
#include<stdio.h> 
#include<string.h> 

int main() {
    char str[] = "Hello, World!";
    memmove(str + 7, str, strlen(str) + 1);
    printf("%s\n", str);
    return 0;
}	

Output:

Hello, Hello, World!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments