POINTERS PART 1
POINTERS IN C LANGUAGE :
Apointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable. In this guide, we will discuss pointers in C with the help of examples.
Before we discuss about pointers in C, lets take a simple example to understand what do we mean by the address of a variable.
A simple example to understand how to access the address of a variable without pointers?
In this program, we have a variable num of int type. The value of num is 10 and this value must be stored somewhere in the memory, right? A memory space is allocated for each variable that holds the value of that variable, this memory space has an address. For example we live in a house and our house has an address, which helps other people to find our house. The same way the value of the variable is stored in a memory address, which helps the C program to find that value when it is needed.
So let’s say the address assigned to variable num is 0x7fff5694dc58
, which means whatever value we would be assigning to num should be stored at the location: 0x7fff5694dc58
. See the diagram below.
#include <stdio.h> int main() { int num = 10; printf("Value of variable num is: %d", num); /* To print the address of a variable we use %p * format specifier and ampersand (&) sign just * before the variable name like &num. */ printf("\nAddress of variable num is: %p", &num); return 0; }
Output:
Value of variable num is: 10 Address of variable num is: 0x7fff5694dc58
A Simple Example of Pointers in C
This program shows how a pointer is declared and used. There are several other things that we can do with pointers, we have discussed them later in this guide. For now, we just need to know how to link a pointer to the address of a variable.
Important point to note is: The data type of pointer and the variable must match, an int pointer can hold the address of int variable, similarly a pointer declared with float data type can hold the address of a float variable. In the example below, the pointer and the variable both are of int type.
#include <stdio.h> int main() { //Variable declaration int num = 10; //Pointer declaration int *p; //Assigning address of num to the pointer p p = # printf("Address of variable num is: %p", p); return 0; }
Output:
Address of variable num is: 0x7fff5694dc58
Comments
Post a Comment