This blog is under construction

Sunday, 29 April 2012

memcpy example in C

Header file:
    string.h

Synopsis:
     void *memcpy(void *dest, const void *src, size_t num);

Description:
     It copies num bytes from src to dest and returns dest.


memcpy function C example:


  #include<stdio.h>
  #include<stdlib.h>
  #include<string.h>

  struct student {
        char name[100];
        int roll_no;
  };

  int main() {
        struct student *ptr1, *ptr2;
        ptr1 = (struct student *) malloc (sizeof (struct student));
        ptr2 = (struct student *) malloc (sizeof (struct student));
        printf("Student name:");
        fgets(ptr1->name, 30,  stdin);
        printf("Roll No: ");
        scanf("%d", &ptr1->roll_no);

        memcpy(ptr2, ptr1, sizeof (struct student));
        printf("\nResult:\nStudent name: %s", ptr2->name);
        printf("Roll no of student: %d\n", ptr2->roll_no);
        return 0;
  }






  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Student name:Robert
  Roll No: 12345

  Result:
  Student name: Robert
  Roll no of student: 12345




1 comment: