简体   繁体   中英

Why is the size of structure pointer **s when derefenced to '*s' and further to 's' is 8 in the below code in C? . Can anybody please explain it

Structure

     struct student
     {
              int rollno;
              char name[10];
              float marks;
     };
     

main Function

     void main()
     {
              struct student **s;
              int n;

Total size of memory to be dynamically allocated

              printf("Enter total number of students:\n");
              scanf("%d",&n);

              printf("Size of **s: %ld\n", sizeof(**s));

Why the size of *s and s is 8 here?

              printf("Size of *s: %ld\n", sizeof(*s));

              printf("Size of s: %ld\n", sizeof(s));

              s = (struct student **)malloc(sizeof(struct student *)* n);

Allocating memory dynamically to array of pointers

              for(int i = 0; i<n; i++)
                   s[i]=malloc(sizeof(struct student));

User defined data

              for(int i = 0; i<n; i++)
              {
                   printf("Enter the roll no:\n");
                   scanf("%d",&s[i]->rollno);

                   printf("Enter name:\n");
                   scanf("%s",s[i]->name);

                   printf("Enter marks:\n");
                   scanf("%f",&s[i]->marks);
              }

              printf("Size of **s:%ld\n",sizeof(**s));
              for(int i = 0; i<n; i++)
                    printf("%d %s %f\n", s[i]->rollno, s[i]->name, s[i]->marks);

              free(s);
     }

Pointer types are as big as they need to be to represent an address on the host system. On x86-64 platforms, all pointer types tend to be 64 bits, or 8 8-bit bytes, wide. The expressions s and *s both have pointer type ( struct student ** and struct student * , respectively), so on your platform they're both 8 bytes wide.

The sizes of pointer types will be different on different platforms, and different pointer types on the same platform may have different sizes. The only requirements are:

  • char * and void * have the same size and alignment;
  • Pointers to qualified types have the same size and alignment as their unqualified equivalents (eg, sizeof (const int *) == sizeof (int *) )
  • All struct pointer types have the same size and alignment;
  • All union pointer types have the same size and alignment.

Why the size of *s and s is 8 here?

Reason: *s is a pointer ( struct student* ), s is a pointer to a pointer ( struct student** ).
And the size of a pointer is 8 bytes (64 bit system)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM