0

Suppose we have

int x = 4;
int *ptr = &x;

I was hoping that ptr[0] would be ptr, ptr[1] would be ptr + 1, etc. However, something completely different happens. I ran

#include <stdio.h>

int main()
{
    int x = 4;
    int* ptr;
    ptr = &x;

    //ptr vs ptr[0]
    printf("ptr: %p\n\n", ptr);
    printf("ptr[0]: %p\n\n", ptr[0]);

    //ptr + 1 vs ptr[1]
    printf("ptr + 1: %p\n\n", ptr + 1);
    printf("ptr[1]: %p\n\n", ptr[1]);

    //ptr + 5 vs ptr[5]
    printf("ptr + 5: %p\n\n", ptr + 5);
    printf("ptr[5]: %p\n\n", ptr[5]);
}

The result was

ptr: 0115FBF4

ptr[0]: 00000004

ptr + 1: 0115FBF8

ptr[1]: CCCCCCCC

ptr + 5: 0115FC08

ptr[5]: 00000001
user56202
  • 299
  • 1
  • 9
  • If you had done `ptr` vs. `&ptr[0]`, `&ptr[1]`, `&ptr[5]`, etc., you would have seen something more like you probably expected. – Steve Summit Nov 11 '21 at 01:05
  • @SteveSummit Than you for the thought-provoking comment. I ran it and I see that `ptr + 1` is the same as `&ptr[1]`. But this introduces another confusion for me. `ptr[1]` is just the content of the 4 contiguous bytes starting at address `ptr + 1`. So I would expect that doing `&ptr[1]` is the same as doing something like `&6`, which results in an error. – user56202 Nov 11 '21 at 01:20

1 Answers1

2

ptr[0] is *(ptr + 0), ptr[1] is *(ptr + 1), etc. Indexing computes the offset and dereferences. You should have gotten a warning about using %p to print something that isn't a pointer.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • That you that makes a lot of sense. I just noticed that I did get warnings. Usually when I don't get errors I become happy and don't look at anything else haha. – user56202 Nov 11 '21 at 00:59
  • @user56202 To reduce any undue happiness, compile with `-Werror` when using gcc or clang, or compile with `/WX` when using microsoft's compiler. [More here](https://stackoverflow.com/questions/57842756/) – user3386109 Nov 11 '21 at 01:04
  • @user3386109 Yes indeed, I should really start paying attention to the warnings. – user56202 Nov 11 '21 at 01:25