2

The question is &str[2], if I write str+2 then it would give the address and its logical but where did I used pointer notation in it?

Should I prefer writing &(*(str+2))?

1
  • 1
    Don't use that last notation; it's just unreadable. Commented Oct 24, 2010 at 19:25

2 Answers 2

4

You can use either

&str[2]

or

(str + 2)

Both of these are equivalent.

Sign up to request clarification or add additional context in comments.

2 Comments

brackets in the 2nd one are necessary?
@fahad Parentheses aren't required. I just added those for readability.
4

This is pointer arithmetic. So when you mention an array str or &str you refer to the base address of the array (in printf for example) i.e. the address of the first element in the array str[0].

From here on, every single increment fetches you the next element in the array. So str[1] and (str + 1) should give you the same result.

Also, if you have num[] = {24, 3}

then num[0] == *(num + 0) == *(0 + num) == 0[num]

6 Comments

There are two mistakes in your answer. First, &(str + 1) shouldn’t work (didn’t actually check but pretty certain) because you can’t use the address-of operator on a pointer. Secondly, &num[0] == num[0] is wrong, and so is the rest of your equation.
@konrad thanks! Just wrote a small snippet to check it out. You were correct! Edited my post.
@Konrad: &(str+1) is invalid because you can't take the address of a temporary variable, not because you can't take the address of a pointer...!
@movieyoda: It's worth clarifying that in the case of a stack array, &str and str are not the same thing. In particular, (str+1) and (&str+1) will not point at the same address (unless the array happens to be of length 1).
@Oli: you’re right of course. But a question about stack arrays (don’t know C …): why do they behave differently? Doesn’t a stack array name decay to a pointer same as a normal array? Or is taking the address of a stack array somehow different from pointer decay?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.