Home > Back-end >  What will happen if I use pointer[Index] in C?
What will happen if I use pointer[Index] in C?

Time:11-17

I'm a beginner in C language, and I was wondering what will happen if I write something like this:

    int *p;
    int b = 4;
    int a = 3;
    p = &a;
    printf("%d", p[1])

I was expecting the result is "4", however, I got an unexpected result(which is a random number)

I also make experiment below: EXP1 EXP2

It makes me more confused. I would like some explantions, thanks.

CodePudding user response:

p[1] points beyond the end of the object to which p points. Dereferencing this pointer is undefined behaviour.

CodePudding user response:

A compiler does not necessarily store objects in the order you define them.

If you handed an assistant a book, a box, and a bottle, and you told them to put the items on a shelf, would you expect they would definitely put them on the shelf in that order? No, they may take whichever one is easiest to manipulate first and put that on the shelf, then another, then another. And they do not care what order you handed them the items if they do not think there is any significance to it.

When you define objects to a compiler, it manages them according to attributes such as size and alignment requirements. And it does not necessarily hold them in the order you define them. It may store them alphabetically in some data structure. Or it may store them in order by a hash code. When it goes to assign memory locations to the items, it may process objects with the strictest alignment requirements first and, within each group, retrieve them either alphabetically or by traversing its own internal data structure.

So, b is not necessarily after a in memory.

But, even if it were, the C standard does not define the behavior of accessing p[1] when p points to a. This means the compiler, when it is analyzing the meaning of your code, as defined by the C standard, can decide that printf("%d", p[1]) has no meaning and can disregard it. As a consequence, compiler optimization can transform programs in surprising ways.

CodePudding user response:

An Interesting thing is you can get 4 when you use clang to compile it(https://tio.run/##S9ZNzknMS///XzkzLzmnNCVVwaa4JCUzXy/Djiszr0QhNzEzT0OTq5pLQQHE1SqwBrIg7CQFWwUTBDcRyDWGcAuATLVEKLsIKJmmoaSaoqSjUBBtGKtpzVX7/z8A), but it's still an undefined behavior and should not use as expect.

  • Related