Why is the result of this mini program 2?

Asked

Viewed 76 times

2

Why the result of this mini program is 2?

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

int main()
{
    int *P = (int *)malloc(10*sizeof(int));
    for(int i = 0; i < 10; i++)
    {
        P[i] = i*10;
    }
    int *Q = P + 8;
    int *L = Q - 2;
    int result = Q - L;
    printf("O resultado e ... : %d\n", result);
    return 0;
}
  • includes #include <stdio. h> #include <stdlib. h>

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

The variable Q points to the memory position equal to the address of P, so the beginning of array, one more shift of 8 positions according to pointer arithmetic, then it is position 8 that has value 80. I highlighted the number that matters here.

L points to this position by returning two positions before, therefore the 6 that has the value 60. Again highlighted the number that matters.

There in result takes the value of Q which is the value of P plus 8, and the value of L is the value of P plus 6 (Q - 2), so we can ignore the value of P, in the background the account is only 8 minus 6, that gives 2. Just looking at the Q - 2 I can see that the result is 2.

Basically, apart from understanding that pointer arithmetic is pure and simple mathematics.

Pointer arithmetic is used to find the relative position of an item in an information set, most notably in arrays. So when sum 1 on the pointer is shifting a position to the next item. The offset always goes according to the element size of the array. The formula is always endereco_inicial + posicao_relativa * tamanho_elemento.

It is possible to do pointer arithmetic on data that is not in arrays, but not this linear displacement.

All this code doesn’t make much sense, starting by allocating memory unnecessarily and then making a meaningless account like that. May be useful for demonstrating pointer arithmetic, but not a good example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.