I have the following form in c (gcc):
typedef struct {
mem 1;
mem 2;
mem n;
} *obj;
How do I get a specific member from that type of structure, initialized with obj var;?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, that declaration is invalid, you’re trying to declare members whose identifiers are numbers. I’ll assume you actually want this:
You access plain struct members with a dot (
.):This is perfectly fine, the compiler allocates stack space of the correct size automatically.
Now, since your
obj varis a pointer1, we’d access its members with an arrow (->):Of course, if you’re lucky, this will segfault. If not, you’re likely to have a very long and enlightening session with the debugger. Unlike declaring a
struct fooitself, Declaringobj varor its equivalentstruct foo *vardoes not create anything except an uninitialized pointer. You need to provide the memory for this yourself:Note that this merely provides the memory, its contents are still undefined, but you can safely assign to them.
1: This is the problem with
typedefing away pointers like you’ve done; it’s impossible to know whether you need to use.or->without seeing the typedef or being told off by the compiler. Don’t usetypedefto hide a pointer.