Sie sind auf Seite 1von 26

JOGINPALLY B. R.

ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

POINTERS

What is Pointer?

Pointer is a user defined data type which creates special types of variables which can hold the address of
primitive data type like char, int, float, double or user defined data type like function, pointer etc. or
derived data type like array, structure, union, enum.Pointers are used in C program to access the memory
and manipulate the address.

How to declaring a Pointer variable?

General syntax of pointer declaration is,

data-type *pointer_name;

Data type of pointer must be same as the variable, which the pointer is pointing. void type pointer
works with all data types, but isn't used oftenly.

How to initialize the Pointer variable?

Initialization of Pointer variable

Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer
variable contains address of variable of same data type. In C language address operator & is used to
determine the address of a variable. The & (immediately preceding a variable name) returns the address
of the variable associated with it.

int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together

Pointer variable always points to same type of data.

float a;
int *ptr;
ptr = &a; //ERROR, type mismatch

1
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

How to Dereferencing a Pointer?

Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.

int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.printf("%u",&p); //this will also print the address
of p.

Discribe about Reference operator(&)?

If var is a variable then, &var is the address in memory.

/* Example to demonstrate use of reference operator in C programming. */


#include <stdio.h>
int main(){
int var=5;
printf("Value: %d\n",var);
printf("Address: %d",&var); //Notice, the ampersand(&) before var.
return 0;
}

Output

Value: 5
Address: 2686778

Note: You may obtain different value of address while using this code.

In above source code, value 5 is stored in the memory location 2686778. var is just the name given to
that location.

You, have already used reference operator in C program while using scanf() function.

scanf("%d",&var);

2
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Discribe about Dereference Operator(*) and Pointer variables?

Pointer variable or simply pointer are the special types of variables that holds memory address rather
than data, that is, a variable that holds address value is called a pointer variable or simply a pointer.

Declaration of Pointer

Dereference operator(*) are used for defining pointer variable

data_type* pointer_variable_name;
int* p;

Above statement defines, p as pointer variable of type int.

Example To Demonstrate Working of Pointers

/* Source code to demonstrate, handling of pointers in C program */


#include <stdio.h>
int main(){
int* pc;
int c;
c=22;
printf("Address of c:%d\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%d\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
c=11;
printf("Address of pointer pc:%d\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
*pc=2;
printf("Address of c:%d\n",&c);
printf("Value of c:%d\n\n",c);
return 0;
}

Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

3
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Explanation of program and figure

1. Code int* pc; creates a pointer pc and a code int c; creates normal variable c. Pointer pc points to
some address and that address has garbage value. Similarly, variable c also has garbage value at
this point.
2. Code c=22; makes the value of c equal to 22, i.e.,22 is stored in the memory location of variable
c.
3. Code pc=&c; makes pointer, point to address of c. Note that, &c is the address of variable
c (because c is normal variable) and pc is the address of pc (because pc is the pointer variable).
Since the address of pc and address of c is same, *pc will be equal to the value of c.
4. Code c=11; makes the value of c, 11. Since, pointer pc is pointing to address of c. Value inside
address pc will also be 11.
5. Code *pc=2; change the contents of the memory location pointed by pointer pc to change to 2.
Since address of pointer pc is same as address of c, value of c also changes to 2.

What is the relation between Arrays and Pointers?

Consider and array:

int arr[4];

In arrays of C programming, name of the array always points to the first element of an array. Here,
address of first element of an array is &arr[0]. Also, arr represents the address of the pointer where it is
pointing. Hence, &arr[0] is equivalent to arr.

4
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0] is arr[0] and
value in address arr is *arr. Hence, arr[0] is equivalent to *arr.

Similarly,

&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).


&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).

In C, you can declare an array and can use pointer to alter the data of an array.

#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
s//Program to find the sum of six numbers with arrays and pointers.
um += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}

Output

Enter 6 numbers:
2
3
4
5
3
4
Sum=21

Discribe about Pointers and Functions - Call by Reference?

When, argument is passed using pointer, address of the memory location is passed instead of value.

5
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Example of Pointer And Functions

Program to swap two number using call by reference.

/* C Program to swap two numbers using pointers and function. */


#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
int temp;
temp=*a;
*a=*b;
*b=temp;
}

Output

Number1 = 10
Number2 = 5

Explanation

The address of memory location num1 and num2 are passed to function and the pointers *a and *b
accept those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the
value of pointer are changed, the value in memory location also changed correspondingly. Hence,
change made to *a and *b was reflected in num1 and num2 in main function.

This technique is known as call by reference in C programming.

Explin about Dynamic Memory Allocation?

The exact size of array is unknown untill the compile time,i.e., time when a compier compiles code
written in a programming language into a executable form. The size of array you have declared initially
can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a
program to obtain more memory space, while running or to release space when no space is required.

Although, C language inherently does not has any technique to allocated memory dynamically, there are
4 library functions under "stdlib.h" for dynamic memory allocation.

6
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Function Use of Function

malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space

calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory

free() dellocate the previously allocated space

realloc() Change the size of previously allocated space

malloc()

The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be casted into pointer of any form.

Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size
of byte size. If the space is insufficient, allocation fails and returns NULL pointer.

ptr=(int*)malloc(100*sizeof(int));

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.

calloc()

The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.

Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);

This statement will allocate contiguous space in memory for an array of n elements. For example:

ptr=(float*)calloc(25,sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size of float,
i.e, 4 bytes.

free()
7
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.

syntax of free()
free(ptr);

This statement cause the space in memory pointer by ptr to be deallocated.

Examples of calloc() and malloc():

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using malloc() function.

#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using calloc() function.

#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
8
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

printf("Enter number of elements: ");


scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

realloc()

If the previously allocated memory is insufficient or more than sufficient. Then, you can change
memory size previously allocated using realloc().

Syntax of realloc()
ptr=realloc(ptr,newsize);

Here, ptr is reallocated with size of newsize.

#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
9
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Describe about Pointers and Arrays?

Pointer and Arrays

When an array is declared, compiler allocates sufficient amount of memory to contain all the elements
of the array. Base address which gives location of the first element is also allocated by the compiler.

Suppose we declare an array arr,

int arr[5]={ 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will
be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0].
Therefore arr is containing the address of arr[0] i.e 1000.

arr is equal to &arr[0] // by default

We can declare a pointer of type int to point to the array arr.

int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one element to another.

NOTE : You cannot decrement a pointer once incremented. p-- won't work.

Describe about Pointer to Array?

10
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access
the array. Lets have an example,

int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}

In the aboce program, the pointer *p will print all the values stored in the array one by one. We can also
use the Base address (a in above case) to act as pointer and print all the values.

Describe about Array of Pointers?

We can also have array of pointers. Pointers are very helpful in handling character array with rows of
varying length.

char *name[3]={
"Adam",
"chris",
11
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};

Describe about Pointer to Function?

It is possible to declare a pointer pointing to a function which can then be used as an argument in
another function. A pointer to a function is declared as follows,

type (*pointer-name)(parameter);

Example :
int (*sum)(); //legal declaraction of pointer to function
int *sum(); //This is not a declaraction of pointer to function

A function pointer can point to a specific function when it is assigned the name of the function.

12
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

int sum(int, int);


int (*s)(int, int);
s=sum;

s is a pointer to a function sum. Now sum can be called using function pointer s with the list of
parameter.

s (10, 20);

Example of Pointer to Function


#include< stdio.h>
#include< conio.h>

int sum(int x, int y)


{
return x+y;
}

int main( )
{
int (*fp)(int, int);
fp=sum;
int s = fp(10, 15);
printf("Sum is %d",s);
getch();
return 0;
}

Output : 25

Describe about Pointers to void?

Void pointer or generic pointer is a special type of pointer that can be pointed at objects of any data
type. A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type.

Pointers defined using specific data type cannot hold the address of the some other type of variable i.e.,
it is incorrect in C++ to assign the address of an integer variable to a pointer of type float.

Example:

float *f; //pointer of type float


int i; //integer variable
f = &i; //compilation error

13
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The above problem can be solved by general purpose pointer called void pointer.

Void pointer can be declared as follows:

void *v // defines a pointer of type void

The pointer defined in this manner do not have any type associated with them and can hold the address
of any type of variable.

Example:

void *v;
int *i;
int ivar;
char chvar;
float fvar;
v = &ivar; // valid
v = &chvar; //valid
v = &fvar; // valid
i = &ivar; //valid
i = &chvar; //invalid
i = &fvar; //invalid

Describe about pointers to pointers?

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer


contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the
address of the second pointer, which points to the location that contains the actual value as shown
below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of
type int:

int **var;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that
the asterisk operator be applied twice, as is shown below in the example:

#include <stdio.h>
14
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

return 0;
}

When the above code is compiled and executed, it produces the following result:

Value of var = 3000


Value available at *ptr = 3000
Value available at **pptr = 3000

What is the Concept of Pointer Compatibility?

The rules for assigning one pointer to another are tighter than the rules for numeric types. For example,
you can assign an int value to a double variable without using a type conversion, but you can’t do the
same for pointers to these two types. Let’s see a simple C program to exemplify this.

#include <stdio.h>
int main(void)
{
int n = 5;
long double x;
int *pi = &n;
long double *pld = &x;
x = n; /* implicit type conversion */
pld = pi; /* compile-time error: assigning pointer-to-int to */
/* pointer-to-long-double */
return 0;
}

These restrictions extend to more complex types. Suppose we have the following declarations:

15
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

int *pi;
int (*pa)[3]; /* pointer to an array of 3 integers */
int ar1[2][3];
int ar2[3][2];
int **p2pi; /* a pointer-to-pointer-to-int, a double pointer */

/* Then we have the following: */


pi = &ar1[0][0]; /* both pointer-to-int */
pi = ar1[0]; /* both pointer-to-int */
pi = ar1; /* not valid because ar1 is an array of 3 integers */

pa = ar1; /* both pointer-to-int[3] */


pa = ar2; /* not valid because ar2 is an array of 2 integers */

p2pi = &pi; /* both pointer-to-int * */


*p2pi = ar2[0]; /* both pointer-to-int */
p2pi = ar2; /* not valid */

Notice that the non valid assignments all involve two pointers that don’t point to the same type.
For example, ‘pi’ points to a single int, but ‘ar1′ points to an array of three ints. Similarly, ‘pa’ points to
an array of three ints, so it is compatible with ‘ar1′, but not with ‘ar2′, which points to an array of two
ints.

The last two examples are somewhat tricky. The variable p2pi is a pointer-to-pointer-to-int, whereas ar2
is a pointer-to-array-of-two-ints (or, more concisely, pointer-to-int[2]). So p2pi and ar2 are of different
types, and therefore we can’t assign ‘ar2′ to ‘p2pi’. But ‘*p2pi’ is of type pointer-to-int, making it
compatible with ‘ar2[0]‘. Recall that ‘ar2[0]‘ is a pointer to its first element, ‘ar2[0][0]‘, making ‘ar2[0]‘
type pointer-to-int also.

In general, multiple indirection is tricky. For instance, consider the next snippet of code:

int *p1;
const int *p2;
const int **p2p;

p1 = p2; /* not valid -- assigning const to non-const */


p2 = p1; /* valid -- assigning non-const to const */

p2p = &p1; /* not valid -- assigning non-const to const */

As we have seen earlier, assigning a const pointer to a non-const pointer is invalid, because we could use
the new pointer to alter const data. But assigning a non-const pointer to a const pointer is okay, provided
that we’re dealing with just one level of indirection:

p2 = p1; /* valid -- assigning non-const to const */

16
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

But such assignments no longer are safe when we go to two levels of indirection. If it were allowed, we
could do something like this:

const int **pp2;


int *p1;
const int n = 13;

pp2 = &p1; /* not allowed, but suppose it were */


*pp2 = &n; /** valid, both const, but sets p1 to point at n */
*p1 = 10; /* valid, but changes const n */

But notice then non-constant pointer-to-int ‘p1′ modified constant integer n. Therefore multi-level
indirection is not allowed.

Explain about Pointer arithmetic and Arrayas?

1.Incrementing Pointer :

1. Incrementing Pointer is generally used in array because we have contiguous memory in array and
we know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable

Formula : ( After incrementing )

new value = current address + i * size_of(data type)


Three Rules should be used to increment pointer -
Address + 1 = Address

Address++ = Address

++Address = Address

Pictorial Representation :

Data Older Address stored in Next Address stored in pointer after incrementing
Type pointer (ptr++)

17
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Data Older Address stored in Next Address stored in pointer after incrementing
Type pointer (ptr++)

int 1000 1002

float 1000 1004

char 1000 1001

Explanation : Incremeting Pointer

 Incrementing a pointer to an integer data will cause its value to be incremented by 2 .


 This differs from compiler to compiler as memory required to store integer vary compiler to
compiler

Note to Remember : Increment and Decrement Operations on pointer should be used when we have
Continues memory (in Array).

Example 1 : Increment Integer Pointer

#include<stdio.h>

int main(){

int *ptr=(int *)1000;

ptr=ptr+1;
printf("New Value of ptr : %u",ptr);

return 0;
}

Output :

New Value of ptr : 1002

Example 2 : Increment Double Pointer

#include<stdio.h>

int main(){

double *ptr=(double *)1000;


18
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

ptr=ptr+1;
printf("New Value of ptr : %u",ptr);

return 0;
}

Output :

New Value of ptr : 1004

Example 3 : Array of Pointer

#include<stdio.h>

int main(){

float var[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];

ptr=&var;
printf("Value inside ptr : %u",ptr);

ptr=ptr+1;
printf("Value inside ptr : %u",ptr);

return 0;
}

Output :

Value inside ptr : 1000


Value inside ptr : 1020

19
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Explanation :

Address of ptr[0] = 1000

We are storing Address of float array to ptr[0]. –

Address of ptr[1]
= Address of ptr[0] + (Size of Data Type)*(Size of Array)
= 1000 + (4 bytes) * (5)
= 1020

Address of Var[0]…Var[4] :

Address of var[0] = 1000


Address of var[1] = 1004
Address of var[2] = 1008
Address of var[3] = 1012
Address of var[4] = 1016

2.Decrementing a pointer:

 Decrementing a pointer to an integer data will cause its value to be decremented by 2


 This differs from compiler to compiler as memory required to store integer vary compiler to
compiler

Pointer Program : Difference between two integer Pointers

#include<stdio.h>

20
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

int main(){

float *ptr1=(float *)1000;


float *ptr2=(float *)2000;

printf("\nDifference : %d",ptr2-ptr1);

return 0;
}

Output :

Difference : 250

Explanation :

 Ptr1 and Ptr2 are two pointers which holds memory address of Float Variable.
 Ptr2-Ptr1 will gives us number of floating point numbers that can be stored.

ptr2 - ptr1 = (2000 - 1000) / sizeof(float)


= 1000 / 4
= 250

Example 2:

#include<stdio.h>

struct var{
char cvar;
int ivar;
float fvar;
};

int main(){

struct var *ptr1,*ptr2;

ptr1 = (struct var *)1000;


ptr2 = (struct var *)2000;

printf("Difference= %d",ptr2-ptr1);

return 0;
}

21
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Output :

Difference = 142

Explanation :

ptr2-ptr1 = (2000 - 1000)/Sizeof(struct var)


= 1000 / (1+2+4)
= 1000 / 7
= 142

3.Adding integer value with Pointer:

In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
In order to compute the final value we need to use following formulae :

final value = (address) + (number * size of data type)

Consider the following example –

int *ptr , n;
ptr = &n ;
ptr = ptr + 3;

Example 1 : Increment Integer Pointer

#include<stdio.h>

int main(){

int *ptr=(int *)1000;

ptr=ptr+3;
printf("New Value of ptr : %u",ptr);

return 0;
}

Output :

New Value of ptr : 1006

Explanation of Program :

22
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

In the above program –

int *ptr=(int *)1000;

this line will store 1000 in the pointer variable considering 1000 is memory location for any of the
integer variable.

Formula :

ptr = ptr + 3 * (sizeof(integer))


= 1000 + 3 * (2)
= 1000 + 6
= 1006

Similarly if we have written above statement like this –

float *ptr=(float *)1000;

then result may be

ptr = ptr + 3 * (sizeof(float))


= 1000 + 3 * (4)
= 1000 + 12
= 1012

4.subtracting integer value from pointer:

Suppose we have subtracted “n” from pointer of any data type having initial addess as “init_address”
then after subtraction we can write –

ptr = initial_address - n * (sizeof(data_type))

Subtracting integer value with Pointer

int *ptr , n;
ptr = &n ;
ptr = ptr - 3;

Live Example 1 : Decrement Integer Pointer

#include<stdio.h>

int main(){

23
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

int *ptr=(int *)1000;

ptr=ptr-3;
printf("New Value of ptr : %u",ptr);

return 0;
}

Output :

New Value of ptr : 994

Formula :

ptr = ptr - 3 * (sizeof(integer))


= 1000 - 3 * (2)
= 1000 - 6
= 994

Summary :

Pointer - Pointer = Integer


Pointer - Integer = Pointer

5. comparing two pointer variables:

Comparison between two Pointers :

1. Pointer comparison is Valid only if the two pointers are Pointing to same array
2. All Relational Operators can be used for comparing pointers of same type
3. All Equality and Inequality Operators can be used with all Pointer types
4. Pointers cannot be Divided or Multiplied

Point 1 : Pointer Comparison

#include<stdio.h>

int main()
{
int *ptr1,*ptr2;

ptr1 = (int *)1000;


ptr2 = (int *)2000;

24
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

if(ptr2 > ptr1)


printf("Ptr2 is far from ptr1");

return(0);
}

Pointer Comparison of Different Data Types :

#include<stdio.h>

int main()
{
int *ptr1;
float *ptr2;

ptr1 = (int *)1000;


ptr2 = (float *)2000;

if(ptr2 > ptr1)


printf("Ptr2 is far from ptr1");

return(0);
}

Explanation :

 Two Pointers of different data types can be compared .


 In the above program we have compared two pointers of different data types.
 It is perfectly legal in C Programming.

As we know Pointers can store Address of any data type, address of the data type is “Integer” so we can
compare address of any two pointers although they are of different data types.

Following operations on pointers :

> Greater Than

< Less Than

>= Greater Than And Equal To

<= Less Than And Equal To

25
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

== Equals

!= Not Equal

6.Divide and Multiply Operations :

#include<stdio.h>

int main()
{
int *ptr1,*ptr2;

ptr1 = (int *)1000;


ptr2 = ptr1/4;

return(0);
}

Output :

26

Das könnte Ihnen auch gefallen