This blog is under construction

Sunday, 29 April 2012

memset example in C

Header file:

     void *memset(void *str, int ch, size_t num);

   It places character ch in first num bytes of str and returns str.

memset function C example:


  struct student {
        char name[30];
        char course[30];

  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("Course: ");
        fgets(ptr1->course, 30, stdin);

        printf("\nResult before memset:\nStudent name: %s", ptr1->name);
        printf("Course: %s\n", ptr1->course);

        ptr2 = (struct student *) memset(ptr1, 'c', sizeof (struct student));
        ptr2->name[29] = '\0';
        ptr2->course[29] = '\0';
        printf("\nResult after memset:\nStudent name: %s\n", ptr2->name);
        printf("Course: %s\n", ptr2->course);
        return 0;

  jp@jp-VirtualBox:~/cpgms/chap5$ ./a.out
  Student name:John milton
  Course: Computer Science

  Result before memset:
  Student name: John milton
  Course: Computer Science

  Result after memset:
  Student name: ccccccccccccccccccccccccccccc
  Course: ccccccccccccccccccccccccccccc

No comments:

Post a Comment