Home > Back-end >  What does the index operator do to arbitrary pointers?
What does the index operator do to arbitrary pointers?

Time:11-11

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

CodePudding user response:

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.

  • Related