Skip to content

Instantly share code, notes, and snippets.

@fatih
Created June 4, 2012 20:30
Show Gist options
  • Select an option

  • Save fatih/2870682 to your computer and use it in GitHub Desktop.

Select an option

Save fatih/2870682 to your computer and use it in GitHub Desktop.
Examples of pointer arithmetics in C
#include <stdio.h>
int main(void)
{
int my_array[] = {13, 4, 9, -5, 45};
int *ptr = NULL;
puts("Now execute ptr = my_array (or ptr = &my_array[0]\n");
// Assing the the addres of my_array(which is of type pointer) to a new pointer (to ptr)
ptr = &my_array[0]; // shorthand: ptr = my_array;
printf("Content of my_array: {13, 4, 9, -5, 45}\n");
printf("Indices my_array[i]: {0, 1, 2, 3, 4, 5}\n\n");
printf("Value of *ptr = %d\n", *ptr);
printf("Address of ptr = %p\n\n", ptr);
printf("Value of *(ptr++) = %d\n", *(ptr++));
printf("Address of ptr = %p\n\n", ptr);
printf("Value of (*ptr)++ = %d\n", (*ptr)++);
printf("Address of ptr = %p\n\n", ptr);
printf("Value of ++*ptr = %d\n", ++*ptr);
printf("Address of ptr = %p\n\n", ptr);
printf("Value of *++ptr = %d\n", *++ptr);
printf("Address of ptr = %p\n\n", ptr);
printf("Value of *ptr-- = %d\n", *ptr--);
printf("Address of ptr = %p\n\n", ptr);
printf("Value of *--ptr = %d\n", *--ptr);
printf("Address of ptr = %p\n\n", ptr);
printf("Value of --*ptr = %d\n", --*ptr);
printf("Address of ptr = %p\n\n", ptr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment