Search code examples
arrayscglobal-variablesmemory-addressint32

(C-Program) example Code about Array Address


#include <stdio.h>

#include <sdint.h>

int32_t a = 0;

void do_stuff(int32_t* c){
    int32_t static b = 2;
    printf("Address: %p\n", c+a);
    printf("%d %d\n", *(c+a),c[b]);
    a+=4;
    b+=b^b;
}

int main() {
    int32_t array[9] = {42, 5, 23, 82, 127, 21, 324, 3, 8};
    printf("Array Address: %p\n", array);
    do_stuff(array);
    do_stuff(array);
    return =0;
}
  • ^ means XOR Operation
  • assume that the printf on line printf("Array Address: %p\n", array); gives you this: Array Address: 0x08

Question: What is the output of this program?

Answer:

0x08

42, 23

0x18

127, 23

My question : why is the output of printf("Address: %p\n", c+a); for the second do_stuff is 0x18?


Solution

  • If not take into account typos in the presented code then after this statement

    a+=4;
    

    the expression c + a points to the fifth element of the array that is the offset from the beginning of the array is equal to 4 * sizeof( int32_t ) that is the same as 4 * 4 and in hex is equal to 0x10.

    So 0x10 + 0x8 == 0x18