0% found this document useful (0 votes)
9 views

Unit 2 pointers

The document provides an in-depth explanation of pointers in the C programming language, detailing their definition, declaration, and usage. It emphasizes the importance of understanding memory organization and the relationship between variables and their addresses. Additionally, it covers pointer arithmetic, the significance of data types in pointer assignments, and includes example programs to illustrate these concepts.

Uploaded by

div29042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit 2 pointers

The document provides an in-depth explanation of pointers in the C programming language, detailing their definition, declaration, and usage. It emphasizes the importance of understanding memory organization and the relationship between variables and their addresses. Additionally, it covers pointer arithmetic, the significance of data types in pointer assignments, and includes example programs to illustrate these concepts.

Uploaded by

div29042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit-2

Pointers
The most intimidating topic in C language is pointers . To understand the concept of pointers we require
complete disciplined approach and a lot of concentration and a few pictures of memory.

Computer’s use their memory for storing the instructions of a program as well as the values of
variables that are associated with it. The computer’s memory is a sequential collection of storage cells.
Each cell commonly known as a byte, has a number called address associated with it. The addresses
are numbered starting from zero. The last address depends on memory size. Whenever we declare a
variable, the system allocates somewhere in a memory an appropriate location to hold the value of the
variable. Since every byte has a unique address number, this location will have its known address
number.
Memory Organization

Consider the following statement, i𝑛𝑡 𝑎 = 179; this statement instructs the system to finda location for
the integer variable ‘a’ and puts the value 179 in that location.

Variable a
Value 179
Address 5000

We may have to access to the value 179 by using either the name ‘a’ or address ‘5000’.

Since, memory addresses are simple numbers; they can be assigned to some variables which can be
stored in memory like any other variable. Such variables that hold memory addresses are called
pointers.

What is Pointer?
A pointer is a variable that contains an address which is a location of another variable in memory. A
pointer enables us to access a variable that is defined outside the function. Pointers reduce the length
and complexity of a program. They increase the execution speed.

Understanding a variable
A variable contains a name, value and address of memory location where it stores itsvalue.

Consider the following variable declaration and memory picture. i𝑛𝑡 i = 50;

The following would be the memory picture after the memory is allocated to variable ‘i’.

Note: All addresses used in this chapter are imaginary. They are used only to let you understand
the concept better. Picture doesn’t show how exactly the value is stored in memory and that is not
important in this case.

So looking at the figure, you would understand that integer variable ‘i’ is allocated two bytes in
memory. First byte is at address 200 and second byte at 201. The value stored inthe variable is 50.
Note: Every memory location contains an address. The address of the variable is always the
address of the first byte of the space allocated to a variable.

Pointer Variable:
A pointer variable or a pointer is similar to a variable but where a variable stores data; a pointer
variable stores address of a memory location. So a pointer does contain all attributes of a variable
but what is stored in pointer is interpreted as an address of a memory location and not as data.

Declaring a pointer
A pointer variable (or pointer) is declared same as a variable but contains a * before thename.

Syntax: 𝑑𝑎𝑡𝑎𝑡𝑦𝑝𝑒 ∗ 𝑝𝑜i𝑛𝑡𝑒𝑟_𝑛𝑎𝑚𝑒;

This tells the compiler three things about the variable ptr_name:
❑ The ∗ tells that the variable ptr_name is a pointer variable.
❑ The ptr_name needs a memory location.
❑ ptr_name points to a variable of a data type.
The following is an example of a pointer variable. int *p; declares the variable p as apointer
variable that points to an integer data type. Remember that the type int refers to the data type of the
variable being pointed to by p and not the type of the value of thepointer. Just like a normal variable
even a pointer variable contains memory location.
Similarly the statement, float *x; declares x as a pointer to a floating point variable.

Note: A pointer always occupies 2 bytes in memory. This is because to store an address we need
only 2 bytes.

Storing address into pointer


A pointer is used to contain an address, to store the address of variable into pointer usingaddress
operator (&). The operator & immediately preceding a variable returns the address of the variable
associated with it.
When a pointer contains the address of a variable, then the pointer is said to be pointing to that
variable. For example, in the following code, pointer p is pointing to variable i.

int i=50,*p;

p = &i;

The memory image for the above assignment is shown in the figure below:

When p contains the address of i then it is read as p is pointing to i .

Accessing a Variable through its pointer


To access the value of the variable using pointer (that contains address of a variable), thisis done by
using another unary operator * (asterisk), usually known as the indirection operator. When a pointer
points to a memory location we can access the value of that memory location using a special
operator called indirection operator (*).

When a pointer variable is used with indirection operator then you get the value of the location to
which pointer points. So *p will return 50 because p is pointing to memorylocation 200 and that is
the location of variable i, where value 50 is stored.

For Example,
int quantity,*p,n;
quantity = 150;
p = &quantity;
n = *p;
❑ The first line declares quantity and n as integer variables and p as a pointer variable of an
integer type.
❑ The second line assigns the value 150 to quantity.
❑ The third line assigns the address of quantity to pointer variable p.
❑ The fourth line contains the indirection operator. When the operator * is placed before a
pointer variable in an expression (on the right hand side of equal sign), the pointer
returns value of the variable of which the pointer value is the address. So, *p returns the
value of the variable quantity, as p is the address of quantity. Thus the value at address p
will be assigned to n, where n value would be 150.
Example: Program to illustrate the concept of pointers.
/*Program to Illustrate the Concept of Pointers*/
#include <stdio.h>
main()
{
int a = 10;
int *p;
p = &a;
clrscr();
printf("\nAddress of a: %u", &a);
printf("\nAddress of a: %u", p);
printf("\nAddress of p: %u", &p);
printf("\nValue of p: %d", p);
printf("\nValue of a: %d", a);
printf("\nValue of a: %d", *(&a));
printf("\nValue of a: %d", *p);
getch();
}
Output:
Address of a: 65494
Address of a: 65494
Address of p: 65496
Value of p: 65494
Value of a: 10
Value of a: 10
Value of a: 10

Example: Program to illustrate the use of indirection operator.


/*Program to Illustrate the use of Indirection operator*/
#include <stdio.h>
main()
{
int x,y;
int *p;
clrscr();
x = 10;
p = &x;
y = *p;
printf("\nValue of x: %d", x);
printf("\n%d is stored at address %u", x,&x);
printf("\n%d is stored at address %u", *p,p);
printf("\n%d is stored at address %u", y,&*p);
printf("\n%u is stored at address %u", p,&p);
printf("\n%d is stored at address %u", y,&y);
*p = 25;
printf("\nValue of x: %d", x);
getch();
}
Output:
Value of x: 10
10 is stored at address 65492
10 is stored at address 65492
10 is stored at address 65492
65492 is stored at address 65496
10 is stored at address 65494
Value of x: 25

Significance of data type


When you declare an integer variable using int i; then i occupies 2 bytes, and float f;would occupy
4 bytes. So the data type determines how many bytes are given to variable.

We must ensure that the pointer variables always point to the corresponding type
of data. For example,
float a,b;
int x,*p;
p = &a;
b = *p;
will result in erroneous output because we are trying to assign the address of a float variable to an
integer pointer. When we declare a pointer to be of int type, the systemassumes that any address
that the pointer will hold will point to an integer variable. Sincethe compiler will not detect such
errors, care should be taken to avoid wrong pointerassignments.

To understand the significance of data type in pointer declaration, you need to understand what
happens when we use * operator. The following example will explain the process involved in using
a pointer.
int i=50;
int *ip;
float f=25.20;
float *fp;
ip=&i;
fp=&f;
printf(“%d %f”,*ip,*fp);

In the above example, ip contains the starting address of i, which is 200. But when we use *ip to get
the value of location pointed by ip we get the value stored in locations200 and 201.

Here are the steps that are taken when a pointer is used with indirection operator (*).
❑ First, the value of pointer variable is taken {*ip = *(200)}
❑ Then it goes to location with that address.
❑ From that address it takes value from n bytes, where n depends on the data type
of the pointer. In case of ip it is int, so it will be two bytes starting from the given
address. {*ip = *(200) = 50}
The same will be the process for *fp, but it will take value from 4 bytes (250 to 253)

Pointer Expressions:
Like other variables, pointer variables can be used in expressions. For example, if p1 and p2 are
properly declared and initialized pointers, then the following statements are valid:
y = *p1 * *p2; same as (*p1)*(*p2)sum
= sum + *p1;
z = 5 * - *p2/ *p1; same as (5 * (-(*p2)))/(*p1)
*p2 = *p2 + 10;
Note that there is a blank space between / and *. The following is wrong:
z = 5 * - *p2/*p1;
As the symbol /* is considered as beginning of a comment and therefore the statement fails.

C allows us to add integers to or subtract integers from pointers, as well as to subtract one pointer
from another: p1 + 4, p2 – 2 and p1 – p2 are all allowed. If p1 and p2 areboth pointers to the same
array then p2 – p1 gives the number of elements between p1 and p2.
We may also use short-hand operators with the pointers.
p1++;

--p2;

sum += *p2;
In addition to arithmetic operators, pointers can also be compared using the relational operators. The
expressions such as p1>p2, p1 = -p2 and p1 != p1 are allowed. Comparisons can be used
meaningfully in handling arrays and strings.

We may not use pointers in division or multiplication. For example, expressions such as p1/p2 or
p1*p2 or p1/3 are not allowed. Similarly, two pointers cannot be added. That is, p1+p2 is illegal.

Example: Program to illustrate the use of pointers in arithmetic operators.


/*Program to Illustrate the use of pointers in arithmetic operators*/
#include <stdio.h>
main()
{
int a,b,*p1,*p2,x,y,z;
clrscr();
a=12;
b=4;
p1=&a;
p2=&b;
x=*p1 * *p2-6;
y=4 * -*p2/ *p1 + 10;
printf("Address of a=%u\n",p1);
printf("Address of b=%u\n",p2);
printf("\n");
printf("a=%d b=%d\n",a,b);
printf("x=%d y=%d\n",x,y);
*p2 = *p2+3;
*p1 = *p2-5;
z = *p1 * *p2-6;
printf("\na=%d b=%d z=%d",a,b,z);
getch();
}
Output:
Address of a=65492
Address of b=65494

a=12 b=4
x=42 y=9

a=2 b=7 z=8

Pointer Increment and Scale Factor – Address Arithmetic


We have seen that the pointers can be incremented like p1 = p2 + 2; p1 = p1 + 1; and soon. However,
an expression like p1++; will cause the pointer p1 to point to the nextvalue of its type.

For example, if p1 is an integer pointer with an initial value, say 2800, then after theoperation
p1=p1+1, the value of p1 will be 2802, and not 2801. That is, when we
increment a pointer, its value is increased by the length of the data type that
it points to.This length is called the scale factor.

The number of bytes used to store various data types depends


on the system and canbe found by making use of the sizeof
operator.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy