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 ?

2
  • Does this answer your question? Accessing arrays by index[array] in C and C++ Commented Mar 25, 2021 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. Commented Mar 25, 2021 at 11:46

1 Answer 1

2

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*.

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

7 Comments

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 ?
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.
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.
'you can treat a pointer like an array, and an array like a pointer'......sometimes.
@MartinJames Let's not get too pedantic here.
|

Your Answer

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