Introduction
This lab will teach you the basics of pointers in C language. You will learn how to create a pointer, access the address and value of a variable using pointers, and print the values using format specifiers.
This lab will teach you the basics of pointers in C language. You will learn how to create a pointer, access the address and value of a variable using pointers, and print the values using format specifiers.
Begin by declaring an integer variable named var
and set its value to 24
. This variable will later be accessed using a pointer.
int var = 24;
Declare a pointer variable named p
that points to an integer value.
int *p;
Point the pointer variable p
to the address of the variable var
using the reference operator &
.
p = &var;
To output the address of the variable var
, use the format specifier %x
.
printf("\n\nAddress of var variable is: %x \n\n", &var);
To output the address stored in the pointer variable p
, use the format specifier %x
.
printf("\n\nAddress stored in pointer variable p is: %x", p);
To access the value of the variable var
using the pointer variable p
, use the dereference operator *
.
printf("\n\nValue of var variable or the value stored at address p is %d ", *p);
Write the complete code in the main.c
file in the ~/project/
directory.
#include <stdio.h>
int main()
{
int var = 24; // actual variable declaration
int *p;
p = &var; // storing address of int variable var in pointer p
printf("\n\nAddress of var variable is: %x \n\n", &var);
// address stored in pointer variable
printf("\n\nAddress stored in pointer variable p is: %x", p);
// access the value using the pointer variable
printf("\n\nValue of var variable or the value stored at address p is %d ", *p);
return 0;
}
Pointers are very powerful in C programming for their ability to access and manipulate memory. By using pointers, you can access and manipulate variables by their addresses directly, which can greatly enhance program efficiency and flexibility. With the knowledge gained in this lab, you can now begin to explore more advanced applications of pointers in your programming endeavors.