Last active
December 2, 2021 19:10
-
-
Save EONRaider/edbd0f22ad6c278658e7a5e65bba24e0 to your computer and use it in GitHub Desktop.
Iterating and modifying an array using pointers in C
This file contains 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> | |
#define SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) | |
void arr_iter(const short[], short); | |
void in_place_mod(short[], short, unsigned int); | |
int main(void) { | |
short numsArr[] = {1, 2, 3, 4}; | |
short SIZE_NUMS = SIZE(numsArr); | |
arr_iter(numsArr, SIZE_NUMS); | |
in_place_mod(numsArr, SIZE_NUMS, 3); | |
return EXIT_SUCCESS; | |
} | |
void arr_iter(const short arr[], short arrSize) { | |
puts("-> Array iteration:"); | |
for (short index = 0; index < arrSize; index++) { | |
// Iterating an array using pointers. No modification of elements. | |
const short *p_element = arr + index; | |
printf("\tpointer + %d: %10p | value = %d\n", index, p_element, *p_element); | |
} | |
} | |
void in_place_mod(short arr[], short arrSize, unsigned int increment) { | |
puts("-> Array modification:"); | |
for (short index = 0; index < arrSize; index++) { | |
// In-place modification of the elements of an array using pointers | |
short *p_element = arr + index; | |
*p_element += increment; | |
printf("\tpointer + %d: %10p | value + %d = %d\n", index, p_element, | |
increment, *p_element); | |
} | |
for (short index = 0; index < arrSize; index++) { | |
/* In-place modification of the elements of an array using index | |
notation, which is just a shorthand for pointer dereferencing! */ | |
arr[index] += increment; // arr[index] == *(arr + index) | |
printf("\tpointer + %hi: %10p | value + %d = %hu\n", index, &arr[index], | |
increment, arr[index]); | |
} | |
} | |
/* SAMPLE OUTPUT: | |
-> Array iteration: | |
pointer + 0: 0x7ffd59722ba0 | value = 1 | |
pointer + 1: 0x7ffd59722ba2 | value = 2 | |
pointer + 2: 0x7ffd59722ba4 | value = 3 | |
pointer + 3: 0x7ffd59722ba6 | value = 4 | |
-> Array modification: | |
pointer + 0: 0x7ffd59722ba0 | value + 3 = 4 | |
pointer + 1: 0x7ffd59722ba2 | value + 3 = 5 | |
pointer + 2: 0x7ffd59722ba4 | value + 3 = 6 | |
pointer + 3: 0x7ffd59722ba6 | value + 3 = 7 | |
pointer + 0: 0x7ffd59722ba0 | value + 3 = 7 | |
pointer + 1: 0x7ffd59722ba2 | value + 3 = 8 | |
pointer + 2: 0x7ffd59722ba4 | value + 3 = 9 | |
pointer + 3: 0x7ffd59722ba6 | value + 3 = 10 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment