You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
814 B
C

#include <stdio.h>
void swap(int *, int *); // defined
int main(void)
{
int a = 21;
int b = 17;
int *p_a = &a; //address of operator. Generates a pointer to the memory location og the object.
int *p_b = &b; // Assigning the pointer &b to the *p_b int pointer variable declared in line
swap(p_a, p_b); //could have done swap(&a, &b); simulates pass-by-reference
printf("main: a = %d, b = %d\n", a, b);
return 0;
}
void swap(int *a, int *b)
{
int t = *a; // dereference the pointer to save it's object's value to the t variable
*a = *b; // *a and *b are both derefencing the int objects at those memory locations. This overwrites the object at location a with b's value.
*b = t; // dereference the b pointer and overwrite it's object's value with the value of t.
}