This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

why pointer doesn't change in struct?

In below code,I think pointer pexam->pf and pf1 will be same, but why pexam->pf++ can't change? What mistake i make? Can someone will help me. thx!

///////////////////////////
struct tagEXAM
{ int x; void (**pf)(void);
};
void fun1(void);
void fun2(void);
void (*code pf[])(void)=
{ fun1,fun2
};
struct tagEXAM code exam[] =
{ {1, pf}
};
int x;
void (**pf1)(void);
struct tagEXAM* pexam;
void main(void)
{ while (1) { pexam = exam; pf1 = pexam->pf;

(*pexam->pf)(); (*pf1)();

pexam->pf++; pf1++; (*pexam->pf)(); (*pf1)();
} }
void fun1(void)
{ x = 1;
} void fun2(void)
{ x = 2;
}

Parents
  • According to the declarations, "exam" is a variable that exists in code memory.

    struct tagEXAM code exam[] =
        {
        {1, pf}
        };
    

    The 8051 cannot write to code memory. (That's a feature.) Therefore, no bits in the variable "exam" can be changed. The type of exam is irrelevant to this point. "pexam" is a pointer to a "struct tagEXAM". This is not a variable in and of itself. It's a pointer, so it just holds the location of some other actual variable.

    struct tagEXAM* pexam;
    

    "pexam" is initialized to point to "exam".

        pexam = exam;
    

    The code then tries to change the "pf" field of the thing to which pexam points:

        pexam->pf++;
    

    The thing to which pexam points is "exam". As we saw at first, "exam" exists in code memory, and so none of it can be changed. pexam->pf is the same memory as exam.pf. It can't be changed. Incrementing would change pf, so you can't increment exam.pf or pexam->pf.

Reply
  • According to the declarations, "exam" is a variable that exists in code memory.

    struct tagEXAM code exam[] =
        {
        {1, pf}
        };
    

    The 8051 cannot write to code memory. (That's a feature.) Therefore, no bits in the variable "exam" can be changed. The type of exam is irrelevant to this point. "pexam" is a pointer to a "struct tagEXAM". This is not a variable in and of itself. It's a pointer, so it just holds the location of some other actual variable.

    struct tagEXAM* pexam;
    

    "pexam" is initialized to point to "exam".

        pexam = exam;
    

    The code then tries to change the "pf" field of the thing to which pexam points:

        pexam->pf++;
    

    The thing to which pexam points is "exam". As we saw at first, "exam" exists in code memory, and so none of it can be changed. pexam->pf is the same memory as exam.pf. It can't be changed. Incrementing would change pf, so you can't increment exam.pf or pexam->pf.

Children