This blog is under construction

Monday 14 May 2012

Structure as function argument in C

A structure variable can be passed as an argument to a function.  It can be either passed by value or passed by reference.  The following example illustrates how to pass structure variable as a function argument.


Structure as function argument example:

  #include <stdio.h>
  #include <string.h>
  struct student {
        char name[100];
        int rollno;
        int age;
  };

  struct student update_static(struct student);
  void update_dynamic(struct student *);

  int main() {
        struct student s1;
        printf("update_static():\n");
        s1 = update_static(s1); // passing structure variable as argument
        printf("Name:%s\nRoll No.:%d\nAge:%d\n",
                s1.name, s1.rollno, s1.age);
        printf("update_dynamic():\n");
        update_dynamic(&s1);// passing address of structure variable as argument
        printf("Name:%s\nRoll No.:%d\nAge:%d\n",
                s1.name, s1.rollno, s1.age);
        return 0;
  }


  struct student update_static(struct student s) {
        strcpy(s.name, "Tom");
        s.rollno = 1010101;
        s.age = 1;
        return s;
  }

  void update_dynamic(struct student *s) {
        strcpy(s->name, "Jerry");
        s->rollno = 2010101;
        s->age = 2;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  update_static():
  Name:Tom
  Roll No.:1010101
  Age:1
  update_dynamic():
  Name:Jerry
  Roll No.:2010101
  Age:2


1 comment:

  1. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete