Skip to content

Instantly share code, notes, and snippets.

@kaivalyar
Created March 13, 2017 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaivalyar/05b20df01eb17a8dccb45f5c556e4c2b to your computer and use it in GitHub Desktop.
Save kaivalyar/05b20df01eb17a8dccb45f5c556e4c2b to your computer and use it in GitHub Desktop.
Simulation to explain answer to pointers question
#include <stdio.h>
int main () {
int c[3] = {4, 5, 6}; // an array is basically a pointer to the first element
void *d = c; // cast int* to void*
d += 1; // increment the void pointer
printf("%08x\n", *((int *)d));
}
#include <stdio.h>
int main() {
int c[3] = {4,5,6};
// for the purposes of this simulation, only the last 3 digits of the memory address of each location are displayed
printf("Lets print our array's memory locations, and their corresponding integer values:\n");
int i = 0;
while (i < 3){
printf("value %02x is stored at address %3p\n", (unsigned)c[i], ((int)(c+i) & 0x00FFF) );
i++;
}// prints the contents at each memory location.
int *d;
d = c;
void *e = c;
printf("\n\nNow lets print the actual contents of memory:\n");
for(i = 0; i < 12; i++){
printf("value %02x is stored at address %02p\n", *(char *)(e+i), ((int)(e+i) & 0x00FFF) );
}
d += 1;
e += 1;
printf("\n\nTherefore:\n");
printf("base address %02p holds (int) value %08x\n\n", ((int)c & 0x00FFF), *c);
printf("integer incremeted address %02p holds integer value %08x \nbecause incrementing an integer pointer moved you forward by %ld bytes\n\n", ((int)d & 0x00FFF), *d, sizeof(*d));
printf("void incremented address %02p holds integer value %08x \nbecause incrementing a void pointer moved you forward by %ld byte\n\n", ((int)e & 0x00FFF), *(int *)e, sizeof(*e));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment