Created
July 26, 2024 19:52
-
-
Save jrelo/dcef995e18d0f089a9673c035fc43d35 to your computer and use it in GitHub Desktop.
C Pointers Demo
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> | |
#include <stdlib.h> | |
#include <string.h> | |
// demonstrate pointer basics | |
void pointerBasics() { | |
int a = 42; | |
int *ptr = &a; | |
printf("Pointer Basics:\n"); | |
printf("Address of a: %p\n", (void*)&a); | |
printf("Value of ptr: %p\n", (void*)ptr); | |
printf("Value pointed by ptr: %d\n", *ptr); | |
} | |
// demonstrate dynamic memory allocation | |
void dynamicMemoryAllocation() { | |
int *array = (int*)malloc(5 * sizeof(int)); | |
if (array == NULL) { | |
fprintf(stderr, "Memory allocation failed\n"); | |
return; | |
} | |
printf("\nDynamic Memory Allocation:\n"); | |
for (int i = 0; i < 5; i++) { | |
array[i] = i * 10; | |
printf("array[%d] = %d (Address: %p)\n", i, array[i], (void*)&array[i]); | |
} | |
free(array); | |
} | |
// demonstrate pointer arithmetic | |
void pointerArithmetic() { | |
int array[5] = {10, 20, 30, 40, 50}; | |
int *ptr = array; | |
printf("\nPointer Arithmetic:\n"); | |
for (int i = 0; i < 5; i++) { | |
printf("ptr + %d points to %d (Address: %p)\n", i, *(ptr + i), (void*)(ptr + i)); | |
} | |
} | |
// demonstrate pointers to pointers | |
void pointersToPointers() { | |
int a = 100; | |
int *ptr = &a; | |
int **pptr = &ptr; | |
printf("\nPointers to Pointers:\n"); | |
printf("Address of a: %p\n", (void*)&a); | |
printf("Value of ptr: %p\n", (void*)ptr); | |
printf("Value of pptr: %p\n", (void*)pptr); | |
printf("Value pointed by pptr: %p\n", (void*)*pptr); | |
printf("Value pointed by *pptr: %d\n", **pptr); | |
} | |
// demonstrate string manipulation with pointers | |
void stringManipulation() { | |
char str[] = "Hello, World!"; | |
char *ptr = str; | |
printf("\nString Manipulation:\n"); | |
printf("Original string: %s (Address: %p)\n", str, (void*)str); | |
while (*ptr != '\0') { | |
printf("Character: %c (Address: %p)\n", *ptr, (void*)ptr); | |
ptr++; | |
} | |
} | |
// demonstrate use of function pointers | |
void functionPointerExample() { | |
void (*funcPtr)(void) = pointerBasics; | |
printf("\nFunction Pointer:\n"); | |
printf("Address of function pointer: %p\n", (void*)funcPtr); | |
funcPtr(); | |
} | |
int main() { | |
pointerBasics(); | |
dynamicMemoryAllocation(); | |
pointerArithmetic(); | |
pointersToPointers(); | |
stringManipulation(); | |
functionPointerExample(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment