Sie sind auf Seite 1von 6

ARITHMETIC OPERATIONS WITH POINTERS

Arithmetic operations on pointer variables are also possible. Increase, decrease, prefix and postfix
operations can be performed with the help of the pointers.

Pointer and Arithmetic Operation

Data type Initial Operation Address Required


address after bytes
operations
int i=2 4046 ++ -- 4048 4044 2
char c=’x’ 4053 ++ -- 4054 4052 1
float f=2.2 4058 ++ -- 4062 4054 4
long l=2 4060 ++ -- 4064 4056 4

Program

#include<stdio.h>

main()

int a=25, b=10, *p, *j;

p=&a;

j=&b;

printf(“Addition a+b=%d\n”, *p+b);

printf(“Subtraction a-b=%d\n”, *p-b);

printf(“Product a*b=%d\n”, *p**j);

printf(“Division a/b=%d\n”, *p/*j);

printf(“Modulo =%d\n”, *p%*j);

Output

Addition a+b=35
Subtraction a-b=15

Product a*b=250

Division a/b=2

Modulo=5

Pointers and Arrays

 Array name by itself is an address or pointer.


 It points to the address of the first element (0th element of an array).
 Array elements are always stored in contiguous memory locations.

Program

#include<stdio.h>

main()

int i;

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

int *p=a;

for(i=0;i<5;i++)

printf("%d\t",*p);

p++;

Output

1 2 3 4 5
Another example program

#include<stdio.h>

main()

int i;

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

for(i=0;i<5;i++)

printf("%d\t",*(a+i));

Output

1 2 3 4 5

Different ways for displaying array elements:

i) a[i]
ii) *(a+i)
iii) *(i+a)
iv) i[a]

Array of Pointers

 C language supports array of pointers.


 It is nothing but a collection of addresses.
 Using this, we can able to store address of variables for which we have to declare an array as a
pointer.

Syntax

data_type *array_name[size];

Example

int *arrp[3];
Program

#include<stdio.h>

main()

int *arrp[3];

int a=10, b=20, c=30, I;

arrp[0]=&a;

arrp[1]=&b;

arrp[2]=&c;

for(i=0;i<3;i++)

printf(“Address = %d\t Value=%d\n”, arrp[i], *arrp[i]);

Pointers and Strings

Creating a string

In the following example, we are creating a string str using the char character array of size 6

char str[6]=”Hello”;

0 1 2 3 4 5

H e l l o \0

1000 1001 1002 1003 1004 1005


Program

#include<stdio.h>

main()

char name[15], *ch;

printf(“Enter your name:”);

gets(name);

ch=name; /* store base address of string name */

while(*ch!=’\0’)

printf(“%c”, *ch);

ch++;

Output

Enter your name: Siva

Siva

Pointers and functions

 Pointer as a function parameter is used to hold addresses of arguments passed during function
call.
 This is known as call by reference.
 When a function is called by reference, any change made to the reference variable will affect
the original variable.

Program

#include<stdio.h>

void swap(int *a, int *b);


int main()

int m=10, n=20;

printf(“m=%d\n”, m);

printf(“n=%d\n”, n);

swap(&m, &n);

printf(“After swapping:\n”);

printf(“m=%d\n”, m);

printf(“”n=%d\n”, n);

return 0;

void swap(int *a, int *b)

int temp;

temp=*a;

*a=*b;

*b=temp;

Das könnte Ihnen auch gefallen