Created
June 4, 2012 20:30
-
-
Save fatih/2870682 to your computer and use it in GitHub Desktop.
Examples of pointer arithmetics in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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