Sunday, July 12, 2009

Help on C++ declarations (pointers and arrays)?

I have a homework assignment and the first question has 4 parts.





It says "Explain the meaning of the following C++ declarations."


(a) double *a [n];


(b) double (*b) [n];


(c) double (*c [n]) ();


(d) double (*d()) [n];





That is the question and here are my guesses.





(a) - I'm thinkg that this is just an array of size n with each element being a pointer to a double.


(b) - maybe its an array of size n with the first element as a pointer to a double.


(c) - this is a prototype of a function that returns an array of size n with each element being a pointer to a double.


(d) - this one is really confusing. I think it might be an array of size n of function d pointing to a double.





Please give me some help. I am not very certain on any of those answers. Thanks a lot for everything.

Help on C++ declarations (pointers and arrays)?
It's tricky to read these types of declarations





a is an array of n pointers to doubles


b is a pointer to an array of n doubles


c is an array of n pointers to functions that return doubles


d is a function returning a pointer to an array of n doubles





Here is the trick. Look at the variable name. Then look at the next element to the right. You can't jump out of any parentheses though. Say what you see, and then look left (but again, don't jump out of parentheses). Say what you see, and jump out a level. Repeat. It's just a matter of look right, look left, jump out, look right, look left, jump out, etc.





So to go through those in more detail:


1) Start at 'a'.


Look right and say "array of size n".


Look left and say "pointers to".


Look right and that's the end of the statement, so don't say anything.


Look left again, and say "double".


Then putting it all together, a is an array of size n pointers to doubles.





2) Do it the same way:


"b is"


look right - hit parentheses, can't do anything.


look left - "a pointer to".


jump out a level.


look right - "array of n"


look left - "doubles"





Maybe I haven't explained it as well as I could have, but here's a website that has a lot of examples, and explains the rule in better detail.





http://www.antlr.org/wiki/display/CS652/...
Reply:O wow, I'm actually in the same class (stumbled onto here by way of Google). I was having trouble with this one myself and just wanted to say thanks for asking it here and thanks to the guy who answered above me, very nice detailed answer.


No comments:

Post a Comment