0

I always took pointer arithmetic for granted. But some times it bugs me, what compiler exactly does, and when do they get evaluated? Consider the program below:

#include <stdio.h>
#include <stdlib.h>

int prng(void);

int main()
{
    int x = prng(); // Pseudo Random Generator.

    int (*a)[x];

    a = malloc(sizeof(int) * 2 * x);    // Allocate 2 rows of x columned vectors

    printf("%p %p\n", a, a + 1);    // How and When does a + 1 evaluate ?

    return 0;
}

I am almost certain that the compiler (or program at runtime) won't ask the CPU to add a and 1 like normal integers for evaluating a+1. So how does the compiler (or program) manage to get the correct addresses?

m0hithreddy
  • 1,752
  • 1
  • 10
  • 17

1 Answers1

0

So how does the compiler (or program) manage to get the correct addresses?

a + 1 is evaluated at run time.

At run time, the size of *a is x * sizeof(int).

The sum is formed by adding to a, x ints to it.


Note:

int (*a)[x]; is UB when x <= 0.

a + 1 is UB when allocation fails.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256