Skip to content

Instantly share code, notes, and snippets.

@emilsoman
Created April 10, 2015 07:29
Show Gist options
  • Save emilsoman/3ddefd41c9d35474ebe9 to your computer and use it in GitHub Desktop.
Save emilsoman/3ddefd41c9d35474ebe9 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int main(){
fprintf(stderr, "%s\n", "Study of int arrays");
fprintf(stderr, "%s\n", "===================");
int a[] = {1, 2, 3, 4, 5};
// Arrays are contiguous memory locations.
// The variable holding the array actually points to
// the first item in the array :
fprintf(stderr, "%p == %p\n", a, &a[0]);
// Add 1 to this pointer and you point to the second item
// in the array, ie, the next integer in the contiguous memory
// NOTE! The next integer was stored 4 bytes after the first
// integer. So integer pointer KNOWS that when you add 1 to it,
// it should move 4 places.
fprintf(stderr, "%p == %p\n", a + 1, &a[1]);
// Interesting to note that you can get any item in the array
// if you have a pointer to an item in the array.
fprintf(stderr, "%d == %d\n", a[0], *(a + 0));
fprintf(stderr, "%d == %d\n", a[1], *(a + 1));
fprintf(stderr, "\n\n");
fprintf(stderr, "%s\n", "Study of char arrays");
fprintf(stderr, "%s\n", "===================");
// Let's see how character pointers work
char c[] = {'a', 'b', 'c', 'd', 'e'};
// Print the address of first item in character array
fprintf(stderr, "%p == %p\n", c, &c[0]);
// Print the address of second item in character array
// NOTE! The next character was stored just 1 byte after the
// prev character because chars occupy only 1 byte of mem.
// So the character pointer just KNEW that if you add 1 to it,
// it should go to a memory location just 1 byte after where it
// was poiting at.
fprintf(stderr, "%p == %p\n", c + 1, &c[1]);
fprintf(stderr, "\n\n");
fprintf(stderr, "%s\n", "Nailing pointer arithmetic");
fprintf(stderr, "%s\n", "==========================");
// Now let's do something crazy. Let's use an integer pointer to
// iterate over a character array!
int *ptr = (int *)c;
fprintf(stderr, "Item at %p = %c\n", ptr, *ptr);
ptr++;
fprintf(stderr, "Item at %p = %c\n", ptr, *ptr);
// See how the pointer moved 4 bytes because we used an integer pointer
// to do the arithmetic ?
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment