1

i was practicing pointers and i saw that when i define a pointer and assign an array to that pointer, i was able to get the value in a specific index when i use the pointer name with that index instead of array name, like,

  int arr[5] = {1,2,3,4,5};
  int *ptr;

  ptr = arr;
  
  printf("%d", ptr[1]); // prints out 2 
 

I was expecting to see the value when i use *ptr[1] and the specific index adress when i use ptr[1], but when i use *ptr[1] i get compiler error. I thought pointer name keeps the adress and using the name with * gives the value in that adress.

Am i missing something here ? Why pointer with array works that way ?

jwdomain
  • 61
  • 7
  • Does this answer your question? [Accessing arrays by index\[array\] in C and C++](https://stackoverflow.com/questions/5073350/accessing-arrays-by-indexarray-in-c-and-c) – Renat Mar 25 '21 at 11:37
  • 2
    `[]` actually always expect a pointer. It does the de-referencing for you, so it's the same as `*ptr` but indexed. – Lundin Mar 25 '21 at 11:46

1 Answers1

3

The misunderstanding here is that pointers and arrays have similar behaviours in C, as in you can treat a pointer like an array, and an array like a pointer.

In effect x[n] is the same as *(x + n) and vice-versa. x[0] is just *x.

As such, ptr[1] will return a de-referenced int* or in other words an int.

If you want the actual address you need to do either ptr + n or &ptr[n], both of which are equivalent, they're int*.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • I think i got it, arrays are just pointers points to multiple adresses and [] operator adds the size of the data type times index with arrays initial adress. am i right ? – jwdomain Mar 25 '21 at 11:48
  • C is not an especially sophisticated language, it's called "fancy assembly" for a reason. A pointer is just an "indirect" way of referring to something, and you can "dereference" it to get that value. Both `x[0]` and `*x` pick out the value the pointer is pointing at. `x[n]` and `*(x + n)` pick out a value `n` places ahead from that pointer. – tadman Mar 25 '21 at 11:50
  • If you look at the assembly output of compiled C code you can see how it's quite literally pointer manipulation and "fetch from address" type operations. – tadman Mar 25 '21 at 11:50
  • 'you can treat a pointer like an array, and an array like a pointer'......sometimes. – Martin James Mar 25 '21 at 12:23
  • @MartinJames Let's not get too pedantic here. – tadman Mar 25 '21 at 12:24
  • @tadman computer systems are really, really pedantic. – Martin James Mar 25 '21 at 12:37
  • @MartinJames When I explain like this it's to paint the general picture. C has so many caveats it goes without saying that general rules do not always apply. Please don't confuse the issue. – tadman Mar 25 '21 at 12:42