tags:

views:

83

answers:

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))?

+3  A: 

You can use either

&str[2]

or

(str + 2)

Both of these are equivalent.

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

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]

MovieYoda
Konrad Rudolph
@konrad thanks! Just wrote a small snippet to check it out. You were correct! Edited my post.
MovieYoda
Now I can upvote. ;-)
Konrad Rudolph
@cool! that's why I love SO
MovieYoda
Oli Charlesworth
Oli Charlesworth
@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?
Konrad Rudolph
@Konrad: A stack-based array (e.g. `int x[5];`) is of array type (`int [5]`). Therefore ` there is no array-to-pointer decay here. This is not true of heap-based arrays (e.g. `int *x = malloc(...);`, because they are necessarily declared as pointers.
Oli Charlesworth
fahad