Search code examples
chexunsigned-integer

Addition of unsigned long and int in C


    int meta_size = 24;
    node_t* prev;

    printf("%lx, ", prev + meta_size );
    printf("%lx, ", prev); 
    printf("%lx, ", meta_size);

out put: 1519240, 1519000, 18 how this is happening?


Solution

  • Prev is a unitialised pointer, it contains (a random, because it is not initialised) memory address.

    printf("%lx, ", prev + meta_size );//Prints the memory address prev is pointing to + (sizeof(node_t) * meta_size)
    printf("%lx, ", prev);             //Prints the memory address prev is pointing to
    printf("%lx, ", meta_size);        //Prints meta_size, 18 is 24 in hexidecimal, because of the 'x' in %lx 
    

    However, the first 2 lines are undefined behaviour because pointers should be printed with %p