Deference Operator

Oct 19, 2012 at 6:09am
So I have been looking around here http://www.cplusplus.com/doc/tutorial/pointers/

Notably this statement "Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by"."

So... If I had

1
2
3
4
5
6
7
int find_file(const dir_t *dir, string file_name, FILETYPE file_type,
int user);
/* REQUIRES: *dir is a valid directory pointer
* EFFECTS: Searches for file with matching name and file_type, which 
* is also accessible by user. If such a file exists, return the file 
* location. Return -1 otherwise.
*/


If I was trying to implement it... would i have to put the deference operator in front of dir?

As in...
1
2
3
for(int i=0; i<*dir.num_files; i++)
{
   if(*dir.files[i]... // and so on 


This is what I would have to do in this case, correct?

Thanks!
Oct 19, 2012 at 6:29am
You could do it like that. To make it clearer you would need to enclose the pointer in parentheses:
(*dir).num_files;

The compiler would resolve the pointer first then access the member.

or you could use ->, which tells the compiler that you want to access the member that the pointer houses.

dir->files[i];
Last edited on Oct 19, 2012 at 6:30am
Oct 19, 2012 at 6:35am
Thanks.

Which would you say is more common? I kind of like the -> better. *'s give me nightmares at the moment. T.T
Oct 19, 2012 at 6:55am
I much prefer the -> too - the reason the -> operator was invented was because pointer access to members is used so much. It makes the code much easier to read as well.
Oct 19, 2012 at 8:45am
With due deference to the OP, the word in this context is dereference (de-reference).
Topic archived. No new replies allowed.