Skip to main content

Pointers to structures

Structure pointers
What is structure pointer?
If the pointer refers to the address of the structure variable, then the pointer is called structure pointer or pointer to structure.
     struct student {
char name[32];
int rollno, marks[5];
float average;
     } obj, *ptr;

     ptr = &obj;

Here, pointer ptr refers to the address of the structure variable obj.

C program using structure pointer:


  #include <stdio.h>
  /* structure st with three different members */
  struct st {
        char ch;
        int num;
        float val;
  } obj, *ptr; // one structure object and a pointer to structure
   int main() {
        /* assigning address of structure variable to pointer */
        ptr = &obj;

        /* assigning values to structure elements using pointer */
        ptr->ch = 'a';
        ptr->num = 10;
        ptr->val = 20.22;

        /* printing the result */
        printf("obj.ch : %c\n", obj.ch);
        printf("obj.num: %d\n", obj.num);
        printf("obj.val: %.2f\n", obj.val);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  obj.ch : a
  obj.num: 10
  obj.val: 20.22



How to access and assign values to structure elements using pointers?
Structure dereference operator is used to assign value to or access structure elements.
          strcpy(ptr->name, "JP");
          ptr->rollno = 5;
          ptr->mark[0] = 100, ptr->mark[1] = 99;
          ptr->average = (100 + 98) / 2;

So, we have assigned values to structure elements using structure dereference operator. The above set of statements is equivalent to 
          strcpy((*ptr).name, "JP");
          (*ptr).rollno = 5;
         (*ptr).mark[0] = 100, (*ptr).mark[1] = 99;
         (*ptr).average = 99.5;

Passing structure pointer to function:
Like other data types, structure pointer can also be passed as function argument.  Below program explains how to pass structure pointer as function argument.


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

  /* structure with 4 data members */
  struct student {
        char name[32];
        int rollno, marks[2];
        float average;
  };

  /* updates value for the given structure object using pointer */
  void update(struct student *ptr) {
        strcpy(ptr->name, "Barack Obama");
        ptr->rollno = 110011;
        ptr->marks[0] = 99;
        ptr->marks[1] = 100;
        ptr->average = (ptr->marks[0] + ptr->marks[1]) / 2.0;
  }

  int main() {
        struct student obj;
        /* passing address of a structure variable as argument */
        update(&obj);

        /* printing the result */
        printf("Name: %s\n", obj.name);
        printf("Roll Number: %d\n", obj.rollno);
        printf("Marks in subject 1: %d\n", obj.marks[1]);
        printf("Marks in subject 2: %d\n", obj.marks[2]);
        printf("Average: %f\n", obj.average);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Name: Barack Obama
  Roll Number: 110011
  Marks in subject 1: 100
  Marks in subject 2: 1120337920
  Average: 99.500000



How to return structure pointer from function?
Below program explains how to return structure pointer from function.


  #include <stdio.h>
  #include <stdlib.h>
  struct op {
        int sum;
        float diff;
  };

  /* finds sum and diff with given input and returns structure pointer */
  struct op * calculate(int x1, int y1, float x2, float y2) {
        struct op *ptr;
        /* dynamic memory allocation for structure */
        ptr = (struct op *)malloc(sizeof(struct op));

        /* assigning values to structure elements */
        ptr->sum = x1 + y2;
        ptr->diff = x2 - y2;
        return ptr;
  }

  int main() {
        struct op *ptr; /* structure pointer declaration */
        ptr = calculate(10, 20, 40.33, 33.22);
        /* printing the result */
        printf("ptr->sum : %d\n", ptr->sum);
        printf("ptr->diff: %.2f\n", ptr->diff);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  ptr->sum : 43
  ptr->diff: 7.11



Dynamic memory allocation for structure:
Let us see how to perform dynamic memory allocation for a structure.
     struct student {
char name[32];
int rollno, marks[5];
float average;
     } *ptr;

    ptr = (struct student *)malloc(sizeof(struct student));

The above statement performs dynamic memory allocation for a structure object using pointers.

Comments

Popular posts from this blog

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...

How to install JDK and setting environment variables for java

In this tutorial, we are going to see the following. How to install JDK How to run java program without setting java path How to set temporary java path in windows How to set permanent java path in windows How to install JDK? Check whether JDK is installed on your PC.  If it is not installed, please go to the below link and download JDK under Java SE(Java Standard Edition) in oracle website . Install the downloaded JDK in your PC. Once JDK is installed, you can run your java program using any method shown below. Having your java source code under jdk/bin, compile the source code and run the program from same directory Setting temporary path for java, compiling the source code and running the program from any location using command prompt Updating the java path in system or user variable(in system properties), compiling the source code and running the program anywhere using command prompt Let us see how to run java program without setting environmental variables.  Once java is ...

Save image in Microsoft Paint without white background

Here, we are going to see how to save image in mspaint without white background 1. Create your own drawing or painting 2. Crop the needed portion of your drawing or painting or image. Here, I am going to crop the porting inside the red box. Now, we have cropped the portion that needs to be saved as an image. 5. Clear the screen and paste the image which we cropped earlier. 6. Decrease the screen size by 50% 7. Now, adjust your screen to fit to your image size. 8. Save the image to desired file format(jpeg, png, bmp etc) 9. Go to the saved location and open the file.  Below is the output image of mine Hope you liked this article!!  For any suggestions, please comment below.