y***6 发帖数: 46 | 1 Hi All,
I just started learning C programming. Can someone help me with the
following C code? Thanks!
------------C code starts here-------------
typedef struct {
int row;
int col;
} MATHEAD;
#define Mathead(a) ((MATHEAD *) (MATHEAD *)(a)-1))
------------C code ends here--------------
My questions are:
i) What does (MATHEAD *)(a)-1 mean? Why minus 1?
ii) What does ((MATHEAD *) (MATHEAD *)(a)-1)) return? |
t****t 发帖数: 6806 | 2 if you can't type, do use copy/paste. the parenthesis in your macro is not
matched.
【在 y***6 的大作中提到】 : Hi All, : I just started learning C programming. Can someone help me with the : following C code? Thanks! : ------------C code starts here------------- : typedef struct { : int row; : int col; : } MATHEAD; : #define Mathead(a) ((MATHEAD *) (MATHEAD *)(a)-1)) : ------------C code ends here--------------
|
y***6 发帖数: 46 | 3 Thanks for pointing that out. I have re-edited my post. |
t****t 发帖数: 6806 | 4 basically i believe you put a MATHEAD structure immediately before your real
data. if A points to your real data; then macro Mathead(A) returns the
pointer to the MATHEAD right before your data.
but i don't think that macro makes sense to cast (a) twice into (MATHEAD*).
it doesn't hurt though.
【在 y***6 的大作中提到】 : Hi All, : I just started learning C programming. Can someone help me with the : following C code? Thanks! : ------------C code starts here------------- : typedef struct { : int row; : int col; : } MATHEAD; : #define Mathead(a) ((MATHEAD *) (MATHEAD *)(a)-1)) : ------------C code ends here--------------
|
m*******e 发帖数: 20 | 5 (i) (MATHEAD *)(a)-1 means you explictely convert pointer "a" into a MATHEAD
type pointer("a" is very likely to be a void* pointer originally), and then
make the pointer point to the memory place immediately before the current
place it does.
(ii) Not very sure about your second question. Actually I think such macro
does not make any sense...Well hope somebody can give out a more precise
answer.
【在 y***6 的大作中提到】 : Hi All, : I just started learning C programming. Can someone help me with the : following C code? Thanks! : ------------C code starts here------------- : typedef struct { : int row; : int col; : } MATHEAD; : #define Mathead(a) ((MATHEAD *) (MATHEAD *)(a)-1)) : ------------C code ends here--------------
|
a***y 发帖数: 2803 | 6 1个int有4个byte,所以一个struct MATHEAD就有8个字节.
(MATHEAD *)(a)-1表示的是减去一个struct单位的地址,也就是减去8个字节.
这是指针类的加减法的特殊的地方.
【在 y***6 的大作中提到】 : Hi All, : I just started learning C programming. Can someone help me with the : following C code? Thanks! : ------------C code starts here------------- : typedef struct { : int row; : int col; : } MATHEAD; : #define Mathead(a) ((MATHEAD *) (MATHEAD *)(a)-1)) : ------------C code ends here--------------
|