Separate names with a comma.
Discussion in 'Mac Programming' started by chris200x9, Dec 19, 2007.
how do you find the address of and element in an array?
Use the address-of operator.
What ChrisBrightwell said. However, I would be interested in knowing why would you want to do that.
int* arr = new int;
arr will give u the value at location 10
arr will give u the address of the first index (0)
&arr will give u the address of the location 10
arr++ will increment the start of the array up one (address)
int* ptr = arr + 10 will give u the address of the location 10
Hope this helps and that I didn't mess up anything here
For a reason I would think you would want to do this is if you had a function that had a let say pointer to an int passed in and you had that value in an array. Then you would want to do
function header ---> void function(int* ptr);
Function call ---> function(&arr);
I'm pretty sure you have to use parenthesis, just to be safe.
int* i = &(array[j]);
Well, you don't have to in this case (because the  operator has higher precedence than the & operator--that is, it is evaluated 1st even without the parens).
But when in doubt (or if you think anyone reading your code would be in doubt), use the parens.
I personally use the following rules, even though I have C++ operator precedence pretty much memorized, for code readability:
1. Generally use parens for everything, except:
2. Don't use parens to show that multiplication and division has a higher precedence than addition and subtraction: that should be natural to every programmer.
3. Don't generally need parens to show that arithmetic operators have lower precedence than pointer or object operators: That should be intuitive for C/C++ programmers and the extra parens would make code hard to read.
4. Don't generally need parens to show that logical operators have lower precedence than arithmetic operators. Same reason as #3.
5. Don't generally need parens to show that assignment operators have lower precedence than (almost) everything else. Same reason as #3.
6. I'll sometimes cut the parens if there are too many already and the intent of the code should be obvious. The overarching goal is code readability, and too many parens can hurt that as well as too few. Obviously you always have to use parens to override the default precedence rules.
I just did this, just a few minutes ago. The usual reason is that you have to pass an address to a function that returns a value in the argument list by reference. I always write it as:
value = funct( &(a) );
Heh, I didn't even consider operator precedence. I just got into the habit when I first started working on a dev team to make code as explicit as possible so that people neither misread my code nor misinterpret my intentions.
It's the same reason I use curly braces for EVERY if/for/etc. block.
Either that or you're passing a big honkin' object and don't want the copy overhead.