Search code examples
cpointerspointer-arithmetic

I don't understand C pointers


I don't really understand the reason why I obtain a different address from what I'm expecting.

I've tried to build this small C code with -m32 flag option.

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

char *Buffer[10];

int main (void){
 printf("%p\n", Buffer);
 char *Buffer2 = Buffer + 6;
 printf("%p\n", Buffer2);
}

Expected output:

Buffer = 0x56559040
Buffer2 = 0x56559046

Obtained output:

Buffer = 0x56559040
Buffer2 = 0x56559058

Why the obtained output is different from the expected one (0x56559040 + 6 = 0x56559046)?


Solution

  • The difference between these two values

    Buffer = 0x56559040
    Buffer2 = 0x56559058
    

    is 0x18 or in decimal 24.

    In this declaration

    char *Buffer2 = Buffer + 6;
    

    the array designator Buffer is converted to pointer to its first element. As the element type of the array Buffer is char * then the expression has the type char **.

    There is no implicit conversion between types char * (the type of the variable Buffer2) and char ** (the type of the initializer)

    So the compiler should issue at least a warning.

    Nevertheless using the pointer arithmetic this expression

    Buffer + 6
    

    is evaluated like

    the value of the address pointed to by Buffer + 6 * sizeof( char * )
    

    as the size of a pointer of the type char * (the size of element of the array) in your system is equal to 4 then you get the value 0x56559058 that is

    0x56559040 + 6 * sizeof( char * )
                     ^^^^^^^^^^^^^^^^
                           4
    

    That is the expression

    Buffer + 6
    

    points to the sixth element of the array Buffer.