Skip to content

Instantly share code, notes, and snippets.

@joegasewicz
Created November 25, 2022 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joegasewicz/abc2b7e943d3221ff2d5d7ec2ee423ee to your computer and use it in GitHub Desktop.
Save joegasewicz/abc2b7e943d3221ff2d5d7ec2ee423ee to your computer and use it in GitHub Desktop.
Pointer Arithmetic
int main()
{
/* ====================================================================== */
/* Pointer Arithmetic */
/* ====================================================================== */
/*
int urn[3];
int *ptr1, *ptr2
Valid:
- ptr1++;
- ptr2 = ptr1 + 2;
- ptr2 = urn + 1;
Invalid:
- urn++;
- ptr2 = ptr2 + ptr1;
- ptr2 = urn * ptr1;
*/
int arraySum(int arrat[], const int sizeOfArray);
int arraySumTwo(int arrat[], const int sizeOfArray);
char charArr[4] = {'a', 'b', 'c'};
char *charPtr = charArr;
printf("charPtr #0 = %c\n", *charPtr); // a
printf("charPtr #1 = %c\n", *(charPtr + 1)); // b
printf("charPtr #2 = %c\n\n", *(charPtr + 2)); // c
// set values
*charPtr = 'd';
*(charPtr + 1) = 'e';
*(charPtr + 2) = 'f';
printf(
"charPtr #0 = %c\n"
"charPtr #1 = %c\n"
"charPtr #2 = %c\n",
*charPtr, *(charPtr + 1), *(charPtr + 2) // d, e, f
);
int values[10] = {3, 7, -9, 3, 6, -1, 7, 9, 1, -5};
int result = arraySumTwo(values, 10);
printf("The sum is %i\n", result);
return 0;
}
/** Adds all items of array together*/
int arraySum(int array[], const int sizeOfArray)
{
int sum = 0, *ptr;
// Cannot change what arrayEnd points to - const is more efficient for the compiler
int *const arrayEnd = array + sizeOfArray; // &arr + 10 = address of end of array
// ptr is a hexadecimal address
for (ptr = array; ptr < arrayEnd; ++ptr)
sum += *ptr; // dereference ptr's each item in the array value
return sum;
}
/**
* Adds all items of array together
* Cut down version, using a pointer to array syntax
*/
int arraySumTwo(int *array, const int sizeOfArray)
{
int sum = 0;
// Cannot change what arrayEnd points to - const is more efficient for the compiler
int *const arrayEnd = array + sizeOfArray; // &arr + 10 = address of end of array
// ptr is a hexadecimal address
for (; array < arrayEnd; ++array)
sum += *array; // dereference ptr's each item in the array value
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment