简体   繁体   中英

accessing struct using pointers

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

struct boo
{
    int c;
    int d;
};

struct foo
{
    struct boo *nest;
    int a;
    int b;
};

int main() {
   struct foo *f1, f2;
   f1 = (struct foo*) malloc(sizeof(struct foo));
   
   f1->nest = (struct boo*)malloc(sizeof(struct boo));
   
   f1->a = 10;
   f1->b = 5;
   f1->nest->c=50;
   f1->nest->d=42;
   
   printf("%d, %d\n", f1->nest[0].c, f1->nest[0].d);
   //50, 42
   printf("%d, %d\n", f1->nest->c, f1->nest->d);
   //50, 42
   
}

why is f1->nest[0].c working? as per my understanding f1->nest, nest is a pointer to struct boo. nest[0] will return the value in the first byte of the address pointed by nest right? how can.c be used to access the member?

The [] operator can be used on any pointer. arr[i] is 100% equivalent to *((arr) + (i)) so between the lines, the + operator is actually the one being used, for pointer arithmetic.

Reading up on the additive operators, then C17 6.5.6/7 says:

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

This means that we can always use any object pointer to perform pointer arithmetic such as ptr + n ... which isn't very meaningful when there is just one single object and not an array. We are still not allowed to access this single object out-of-bounds.

Although because of the previous explained equivalence between pointer arithmetic and the [] operator, this also means that we can always do arr[0] to dereference any object pointer, no matter if it is an array or not.


nest[0] will return the value in the first byte of the address pointed by nest right?

No, it will return the value of the first struct , in a list of 1 single struct. It is the same as writing the more obscure (*(f1->nest + 0)).c

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