Introduction
In C programming, pointers are powerful features that allow us to manipulate data by accessing and modifying memory locations directly. One common application of pointers is swapping values between two variables without using a third variable.
In this lab, we will learn how to create a C program that swaps two numbers using pointers. This technique is fundamental in various programming scenarios and demonstrates the practical use of pointers for memory manipulation.
The lab will guide you through creating a program from scratch, compiling it, and running it to see the swap in action.
Understanding Pointers in C
Before we start coding, let's understand what pointers are and how they work in C.
What is a Pointer?
A pointer is a variable that stores the memory address of another variable. Pointers are essential in C because they allow direct access to memory and enable more efficient manipulation of data.
Pointer Syntax
In C, pointers are declared using the asterisk (*) symbol:
int *ptr; // Declares a pointer to an integer
When working with pointers, we use two important operators:
- The address-of operator (
&) - gets the memory address of a variable - The dereference operator (
*) - accesses the value stored at the address held by a pointer
Creating Our First File
Let's start by creating our main C file in the project directory. Open the IDE and create a new file named main.c:
- In the file explorer panel (left side), navigate to
/home/labex/project - Right-click and select "New File"
- Name the file
main.c - Add the following basic structure to the file:
#include <stdio.h>
int main() {
// We will add our code here
return 0;
}
This creates a simple C program with the standard input/output library included and a main function that returns 0 when the program completes successfully.
Creating the Swap Program Structure
Now that we understand pointers, let's build our swap program step by step.
Declaring Variables and Pointers
We need to declare:
- Two integer variables (
aandb) to hold the values we want to swap - Two integer pointers (
ptraandptrb) to store the addresses ofaandb - A temporary variable (
temp) to help with the swap operation
Update your main.c file with the following code:
#include <stdio.h>
int main() {
// Declare variables
int a, b;
int *ptra, *ptrb;
int temp;
// Get input from user
printf("Enter value for a: ");
scanf("%d", &a);
printf("Enter value for b: ");
scanf("%d", &b);
// Display original values
printf("\nOriginal values:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
// We will add more code here in the next step
return 0;
}
Understanding the Code
Let's analyze what we've done so far:
- We declared two integers
aandbthat will hold the values we want to swap - We declared two integer pointers
ptraandptrbthat will store the memory addresses ofaandb - We declared a temporary integer
tempthat will help us with the swap operation - We added code to prompt the user to enter values for
aandb - We added code to display the original values of
aandb
Notice that in the scanf function, we use the address-of operator (&) to tell the function where to store the input values in memory.
Implementing the Swap Logic
Now let's implement the actual swap logic using pointers.
Assigning Addresses to Pointers
First, we need to make our pointers point to our variables by assigning the addresses of a and b to ptra and ptrb respectively:
// Assign addresses to pointers
ptra = &a;
ptrb = &b;
The Swap Algorithm Using Pointers
The key to swapping values with pointers is to manipulate the values at the memory locations, not just the pointers themselves. Here's how we'll do it:
- Store the value of
a(accessed via*ptra) in the temporary variabletemp - Assign the value of
b(accessed via*ptrb) toa(by using*ptra) - Assign the temporary value (original value of
a) tob(by using*ptrb)
Update your main.c file by adding the following code where indicated in the previous step:
#include <stdio.h>
int main() {
// Declare variables
int a, b;
int *ptra, *ptrb;
int temp;
// Get input from user
printf("Enter value for a: ");
scanf("%d", &a);
printf("Enter value for b: ");
scanf("%d", &b);
// Display original values
printf("\nOriginal values:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
// Assign addresses to pointers
ptra = &a;
ptrb = &b;
// Display memory addresses (optional but helpful for understanding)
printf("\nMemory addresses:\n");
printf("Address of a: %p\n", ptra);
printf("Address of b: %p\n", ptrb);
// Swap the values using pointers
temp = *ptra; // Store value of a in temp
*ptra = *ptrb; // Assign value of b to a
*ptrb = temp; // Assign original value of a to b
// Display swapped values
printf("\nAfter swapping:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
Understanding the Swap Logic
Let's understand exactly how the swap works:
temp = *ptra;- The*operator dereferences the pointer, accessing the value at the memory location. This line stores the value ofaintemp.*ptra = *ptrb;- This assigns the value ofbto the memory location ofa, effectively changinga's value.*ptrb = temp;- This assigns the original value ofa(stored intemp) to the memory location ofb, completing the swap.
After these operations, the variables a and b have exchanged values without directly modifying them - we only modified the values at their memory locations.
Compiling and Testing the Swap Program
Now that we have completed our program, let's compile and run it to see the results.
Compiling the Program
To compile the program, we'll use the GNU C Compiler (gcc). Open a terminal in the WebIDE and run the following command:
cd ~/project
gcc main.c -o swap_program
This command compiles our main.c file and creates an executable named swap_program.
Running the Program
Now let's run our program to see if it correctly swaps the values:
./swap_program
You'll be prompted to enter values for a and b. For example, let's enter:
a= 5b= 10
The program should display:
- The original values: a = 5, b = 10
- The memory addresses of a and b
- The swapped values: a = 10, b = 5
Understanding the Output
When you run the program, you'll see several sections of output:
- Original values - Shows the values before swapping
- Memory addresses - Shows where the variables are stored in memory (will be different each time you run the program)
- After swapping - Shows the values after the swap operation
Try running the program multiple times with different input values to confirm that the swap works consistently.
How Does It Work Behind the Scenes?
Let's visualize what happens in memory:
- Initially, if
a = 5andb = 10, they each have their own memory locations ptrapoints to the memory location ofaptrbpoints to the memory location ofb- During the swap:
tempgets the value atptra(which is 5)- The value at
ptrais changed to the value atptrb(which is 10) - The value at
ptrbis changed totemp(which is 5)
- After the swap,
a = 10andb = 5, effectively swapping their values
This demonstrates the power of pointers - they allow us to indirectly modify values by manipulating memory locations directly.
Summary
In this lab, we learned how to use pointers in C to swap the values of two variables. Key concepts covered include:
- Pointers: Variables that store memory addresses of other variables
- Memory Addresses: Unique locations in computer memory where data is stored
- Pointer Operations:
- The address-of operator (
&) to get a variable's memory address - The dereference operator (
*) to access the value at a memory address
- The address-of operator (
- Swap Algorithm: Using a temporary variable and pointers to exchange values
This technique is a fundamental concept in C programming and demonstrates the power of pointers for memory manipulation. It can be applied in various programming scenarios such as sorting algorithms, data structure operations, and function implementations.
By understanding how to manipulate data through memory addresses, you've taken an important step in mastering C programming and computer memory concepts.



