This blog is under construction

Sunday, 29 April 2012

memset example in C

Header file:
    string.h

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

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


memset function C example:


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

  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;
  }



  Output:
  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



1 comment:

  1. Do you need Finance? Are you looking for Finance? Are you looking for finance to enlarge your business? We help individuals and companies to obtain finance for business expanding and to setup a new business ranging any amount. Get finance at affordable interest rate of 3%, Do you need this finance for business and to clear your bills? Then send us an email now for more information contact us now via (financialserviceoffer876@gmail.com) whats-App +918929509036 Dr James Eric Finance Pvt Ltd Thanks

    ReplyDelete