Structure and pointers arithmetic

Viewed 105
#include <stdio.h>

struct student
{
  int roll_no;
  int total_marks;
} s1;

int main()
{
  struct student *stu;
  stu = &s1;
  printf("Address of member roll_no accessed by s1 = %u", &s1.roll_no);
  printf("Address of member total_marks accessed by s1 = %u", &s1.total_marks);
  printf("Value of stu = %u", stu); // which is address of s1.roll_no

Likewise, how do I get the address of s1.total_marks using stu?

Figured it completely. Lets just say we have structure like this: Every single one those members can be accessed in the following way,

   #include <stddef.h>   

   struct student    
   {   
      int roll_no;   
      char name[50];   
      double mark;   
      double percetage;   
   };   

   int main()   
   {   
   struct student s = {1, "Jug", 98.99, 97.5678};   
    
       printf("%d %s\n", *(int*)((char*)&s + offsetof(struct student,    
   roll_no)), (char*)((char*)&s + offsetof(struct student, name)));      
       printf("%lf %lf", *(double*)((char*)&s + offsetof(struct student,  
  mark)), *(double*)((char*)&s + offsetof(struct student, percentage)));        
   }```
2 Answers

Member access operators (., ->) have higher precedence than the address-of operator (&). So &p->m is not equivalent to (&p)->m, but rather to &(p->m).

Hence, you can use

&stu->total_marks

as well as you already wrote

&s1.total_marks

As stu is a pointer to s1, just do:

&(stu->total_marks)
Related