Interesting C struct syntax/type
I came across this in the Python interpreter source code.
void
PyThread_delete_key_value(int key)
{
long id = PyThread_get_thread_ident();
struct key *p, **q;
The interesting part being the struct key *p, **q;
call. What exactly is this structure doing? I'm confused as to what exactly this is a struct of. Is this not the same as say, this?
struct 1 *p;开发者_开发技巧
I are confused.
Edit:
Even though this has been answered, I should clear up my question. It was specifically the fact that the word key
was reused and that I didn't know that the compiler considers them in different namespaces.
key exists in two different namespaces here. Once as a variable, once as a structure. The compiler knows that 'struct key' and int key are different things.
p
is a pointer to an object of type struct key
. q
is a pointer to a pointer of an object of type struct key
.
You can define a structure like so:
struct key { int val; };
In which case the type is struct key
.
The key
after struct
is part of the type (struct key
), and not associated with the integer parameter key
.
Those are pointers to struct. p is a point to key struct, and q is a pointer to a pointer of key struct. It is hard to tell what is going on here with out seeing the struct typedef or how the pointers are being used.
First, the int key
parameter has nothing to do with the struct key
in the declaration. That is just an unfortunate naming collision.
Structs are in a different namespace though, so it works.
The line
struct key *p, **q;
Is declaring two variables.
The first is named p
and is of type struct key *
.
The second is named q
and is of type struct key **
.
The asterisk, denoting a pointer type, binds to the variable name not to the overall type in the declaration.
As an aside, as I commented in mipadi's answer, I had a professor who supposedly asked Kernighan (or maybe it was Ritchie) why it was the case that C expressions mirror their declarations in syntax. He said it was to be able to re-use the same parsing code. Apparently the C compiler was pretty close to being too-big-to-fit on the system it was written for.
It is nice sometimes, since you can be sure that if you have the declaration
int **foo[];
Then the expression
**foo[3]
Will be of type int
, without having to think too hard about it.
精彩评论