Home > Mobile >  Difficulty understanding the expression (*(&x->y))
Difficulty understanding the expression (*(&x->y))

Time:11-04

I have the following file structure. I am aware that a pointer needs allocated memory. File A is generated by DaVinci. The main is written by me.

// File A
typedef struct {
    int v1;
}s1;

struct s2{
    s1 *p1;
};

extern const struct s2 * const p3;  // Expr 1
#define untilp1() (*(&p3->p1))  // Expr 2

// File main
#include <stdio.h>
#include "FileA.h"
int main()
{
    int v2 = 10;
    untilp1()->v1 = v2;  // This line results in failure
    return 0;
}
    

Q1 - I don't understand the expression 1. Specifically, I do not understand the use of so many const keywords in expr 1. I am aware of the meaning of the term extern. In this case, I guess a constant pointer p3 is undefined, undeclared but the compiler knows it points to constant structure s2. Is this correct? Please elaborate if you can make it clearer.

Q2 - I do not understand expression 2. Specifically, I don't understand what's happening with (*(&p3->p2)). I know the meaning of #define. Please explain the expression in a detailed way.

Q3 - In general coding, I allocate memory e.g. using malloc before I declare using pointers. I am not sure how is this handled when these files are generated by DaVinci. But I haven't seen any of my colleagues using malloc etc. Does anyone know if I can allocate the value of v2 to v1 using p3 or untilp1()?

Thank You.

CodePudding user response:

Q1: p3 is a const pointer (meaning that the pointer itself may not be changed) to a const struct s2 meaning that the struct s2 can not be changed either.

Q2: *(&p3->p1) takes the address of struct p3's member p1 and then dereferences it. With that macro definition the assignment needs to be: (untilp1())->v1 = v2;. See Operator Precedence. My recommendation is to put the parantheses in the macro instead.

Q3: "In general coding" - I think that needs a separate question. It may be opinion based.

Demo

  • Related