Search code examples
cpointersmallocdynamic-allocationcalloc

Pointer arithmetic and malloc()/calloc() functions


There're 2 things I don't understand, usually when using malloc() / calloc() we type cast the it because they return a void pointer so we type cast it to our pointer type so we could do pointer arithmetic with it. So I've made a code example where I use malloc() and I don't type cast it and the pointer arithmetic still works :

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

int main()
{
    int *p = malloc(8);
    *p++ = 30;
    *p = 40;
    printf("p points to address [%p] which holds a value of %d, p points to address [%p] which holds a value of %d\n", p, *p++, p, *p--);
    return 0;
}

why is that ?

Another question of mine regarding to pointers arithmetic is that the code I showed you above, I originally wrote it as follow :

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

int main()
{
    int *p = malloc(8);
    *p++ = 30;
    *p-- = 40;
    printf("p points to address [%p] which holds a value of %d, p points to address [%p] which holds a value of %d\n", p, *p++, p, *p--);
    return 0;
}

Notice the difference is *p-- = 40. I've use p-- because I wanted to print the correct address the pointer was pointing at, I was assuming that after I use p++ I need to use p-- so the pointer will point at the address of the value of 30, but if I added the p-- and printed it I've noticed that it prints another value. So something here doesn't click for me what's going on with it ? Also if I removed the -- and then printed, it printed 30 and then 40 as I expected BUT the address remained the same, I've expected it to be the previous address+4 which it wasn't yet the value changed, what's going on ?

https://i.sstatic.net/A3t6K.jpg


Solution

  • Pointer arithmetic depends on the type with which your pointer is declared. Since your pointer is int *, then ++ and -- will increment and decrement the (raw) value of the pointer by sizeof(int) so that you can access adjacent int values.

    In C, it is possible to assign a void * to another type of pointer (such as int *) without triggering a warning (this is not true in C++). In this case the cast is implicitly performed by the compiler.