C Online Compiler
Example: Pass by Reference using Pointers (Swap Example) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Pass by Reference using Pointers (Swap Example) #include <stdio.h> // Function to swap two integers using pointers (pass by reference) void swapByReference(int *ptrA, int *ptrB) { // Step 1: Declare a temporary variable to hold one of the values. // Use '*' to dereference ptrA, accessing the value it points to. int temp = *ptrA; // Step 2: Assign the value pointed to by ptrB to the location pointed to by ptrA. *ptrA = *ptrB; // Step 3: Assign the temporary value (original *ptrA) to the location pointed to by ptrB. *ptrB = temp; printf("Inside function: *ptrA = %d, *ptrB = %d\n", *ptrA, *ptrB); } int main() { int num1 = 10; int num2 = 20; printf("Before swapByReference: num1 = %d, num2 = %d\n", num1, num2); // Call swapByReference, passing the memory addresses of num1 and num2 // The '&' operator gets the address of the variable. swapByReference(&num1, &num2); printf("After swapByReference: num1 = %d, num2 = %d\n", num1, num2); return 0; }
Output
Clear
ADVERTISEMENTS