Serving the Quantitative Finance Community

 
User avatar
accelas
Topic Author
Posts: 0
Joined: September 24th, 2008, 5:53 am

C programming pointer trick

September 11th, 2009, 7:59 pm

My company uses this question in pre-interview test. After I learn the answer, I find it very clever. And this is actually pretty practical: I know one major open source project uses this trick extensively.QUESTION 8: Given a pointer to member a within a struct, write a routine that returns a pointer to the struct.struct s {... int a;…}; struct s *get_s_ptr(int *a_ptr){// implement this.}
 
User avatar
jikan
Posts: 0
Joined: April 9th, 2008, 10:07 am

C programming pointer trick

September 11th, 2009, 10:02 pm

struct s* get_s_ptr(int *a_ptr){ return (struct s*)((char*)a_ptr - (int)&((struct s*)0)->a);}Hope there's no typo .
Last edited by jikan on September 11th, 2009, 10:00 pm, edited 1 time in total.
 
User avatar
accelas
Topic Author
Posts: 0
Joined: September 24th, 2008, 5:53 am

C programming pointer trick

September 11th, 2009, 10:18 pm

that's right XD, and that's how linux kernel implements its linked list. I handles all the pre-interview tests for my company (but i don't make decision, I just arrange and administrate the test). 2 years and hundreds of applicant, the # of ppl who got that right is a single digit.
 
User avatar
ehremo
Posts: 0
Joined: April 22nd, 2005, 9:49 am

C programming pointer trick

September 14th, 2009, 5:48 am

not exactly great programming style though.
 
User avatar
Cuchulainn
Posts: 23029
Joined: July 16th, 2004, 7:38 am

C programming pointer trick

September 14th, 2009, 10:38 am

QuoteMy company uses this question in pre-interview test.What kind of company is your company? You are looking for a special skill? QuoteHope there's no typo I suppose we'll never know! undocuments code
Last edited by Cuchulainn on September 13th, 2009, 10:00 pm, edited 1 time in total.
 
User avatar
accelas
Topic Author
Posts: 0
Joined: September 24th, 2008, 5:53 am

C programming pointer trick

September 14th, 2009, 3:57 pm

To Cuchulainn:Our company makes firewall and related network equipment. The coding is either 1)kernel module or 2)low level daemon. I'm just a junior developer who happened to have some HR duty that was not a part of job description...To ehermo:Well, it is kind of confusion. Normally a container structure contains the element. but in this case, the element contains the container structure node. You can iterate/search the container structure node, then uses a macro to extract element. One advantage is that you can easily have an element belongs to multiple container structure. My company actually used this style for many other data structure too: hash table, trees etc.