0% found this document useful (0 votes)
18 views18 pages

Pointers

The document discusses pointers in C programming, detailing their purpose, declaration, and operations. It explains how pointers can be used to pass data between functions, access array elements, and perform pointer arithmetic. Additionally, it covers the concept of null pointers and generic pointers, emphasizing their significance in modifying data across functions.

Uploaded by

vini t
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)
18 views18 pages

Pointers

The document discusses pointers in C programming, detailing their purpose, declaration, and operations. It explains how pointers can be used to pass data between functions, access array elements, and perform pointer arithmetic. Additionally, it covers the concept of null pointers and generic pointers, emphasizing their significance in modifying data across functions.

Uploaded by

vini t
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/ 18

III Unit Remaining Part- POINTERS  to pass information back and forth between a function and its reference

point.
Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers  Enable the programmers to return multiple data items from a function
– Array of pointers – Example Program: Sorting of names-Parameter via function arguments.
passing : Pass by value, Pass by reference – Example Program:  Provide an alternate way to access individual elementsof the array.
Swapping of 2 nos and changing the value of a variable using pass by  To pass arrays and strings as function arguments.
reference  Enable references to functions. So with pointers, theprogrammer can
even pass functions as argument toanother function.
3.9 INTRODUCTION
3.10 DECLARING POINTER VARIABLES
 Every variable in C language has a name and a value associated
with it.  A pointer provides access to a variable by using the address of that
 When a variable is declared, a specific block of memory within the variable.
computer is allocated to hold value of that variable.  A pointer variable is therefore a variable that stores the address of
 Every variable in C has a value and a memorylocation(commonly another variable.
known as address) associated with it.  The general syntax of declaring pointer variables
 Some texts use the term rvalueand lvaluefor the value and the address data_type *ptr_name;
of the variable, respectively. Here, data type is the datatype of the value that the pointer will point to.
 The rvalue appears on the right side of the assignment statement (10 For example,int *pnum;
in the above statement) and cannot be usedon the left side of the  Eg:
assignment statement. intx=10;
 If we write int *ptr;
int x, y; ptr = &x;
x=10;  ptr is the nameof pointer variable.
y=x;  The ‘*’informs the compiler that ptr is a pointer variable and the
 Actually pointers are nothing but memory addresses. intspecifiesthat it will store the address of an integer variable.
 A pointeris a variable that contains the memory location of another  An integer pointer variable points to an integer variable.
variable.  The last statement, ptr is assigned the address of x.
 The &operatorretrievesthelvalue (address) of x, and assigns it to the
APPLICATIONS pointer ptr.

1
return 0;
}
Output:
Enterthe number: 10
The numberthat was entered is: 10
The address of number in memory is: FFDC

%p control stringprints the argumentas a memory address hexadecimal


form.
%uprints memory address in decimal form.

Eg:
#inc1ude <stdio.h>
int main()
 In C, pointers are not allowed to store actual memory addresses,but {
only the addresses of variables of a giventype. intnum,*pnum;
 Therefore writing a statement like int *ptr = 1000;isabsolutelyillegal in pnum = &num;
C. *pnum = 10;
 We can dereference a pointer, i.e., refer to the value of the variable printf(" \n *pnum = %d", *pnum);
to which it points, by using unary '* ' operator (also known as printf("\n num = %d", num);
indirection operator) *pnum = *pnum + 1;
printf (" \nAfter increment *pnum= %d ”, *pnum);
Eg: printf (" \nAfter increment num = %d", num) ;
#include<stdio.h> return 0;
int main() }
{ Output
intnum, *pnum; *pnum = 10
pnum= &num; num = 10
printf ("\n Enter the number: "); After increment *pnum = 11
scanf ("%d", &num); After increment num = 11
printf ("\n The number that was enteredis: %d",*pnum) ;
printf ("\n The address of number inmemoryis: %p",&num);

2
ptrl=&numl;
ptr2 = &num2;
Eg: sum = *ptr1 + *ptr2;
int x = 10; mul = sum * *ptr1;
float y = 2.0; *ptr2 +=1;
int *px; div = 9 + *ptrl/*ptr2 - 30;
float *py;
px= &y;//INVALID  C also allows to pointers by using relational operators in the
py = &x;//INVALID expressions.
 For example,
Eg: pl> p2, pl == p2, and p1!= p2 are all valid in C.
#include <stdio.h>  When using pointers, unary increment (++) and decrement (--)
int main() operators have greater precedence than the dereference operator
{ (*).
int a=3, b=5;  Both these operators have a special behaviour when used as suffix.
int *pnum;  In thatthe expression is evaluated with the value it had before being
pnum = &a; increased.
printf ("\n a %d", *pnum);  Therefore, the expression *(ptr++) as ++ has greater operator
pnum = &b; precedence than *.
printf ("\n b %d", *pnum);  Therefore, the expression will increment tthe value of ptr so that it now
return 0; points to the next increment location.
}  Therefore, to increment the value of the variable whose address is stored
in ptr, youwrite(*ptr)++
Output
a=3 Eg:
b=5 int num1=2, num2=3;
int *p = &numl, *q=&num2;
3.11 POINTER EXPRESSIONS AND POINTER ARITHMETIC *p++ = *q++;
 What will *p++ = *q++ do? Because ++ has a higherprecedence than *,
 Pointer variables can also be used in expressions. both p and qare increased, but becausethe increment operators (++) are
Eg: used as postfix and notprefix, the value assigned to *p is *q before both
int num1=2, num2= 3, sum=0, mul=0, div=0;
int *ptr1, *ptr2;
3
p and qare increased. Then both areincreased. So the statement is float num1,num2,sum=0.0;
equivalent to writing:*p = *q;++p; ++q; float *pnum1=&num1, *pnum2=&num2;
Summarize the rules for pointer operations: *psum=&sum;
printf("\n Enter the two numbers: ");
 A pointer variable can be assigned the address ofanother variable (of the scanf("%f %f", pnum1, pnum2);
same type). *psum = *pnum1 + *pnum2;
 A pointer variable can be assigned the value of anotherpointervariable printf("\n %f + %f = %.2f", *pnum1,*pnum2, *psum);
(of the same type). return 0;
 A pointer variable can be initialized with a NULL (or value) }
 Prefixor postfix increment and decrement operators canbe applied on a o/p:
pointer variable. Enter the two numbers: 2.5 3.4
 An integer value can be added or subtracted from apointervariable. 2.5 + 3.4 = 5.90
 Apointervariable can be compared with another pointervariableof the
same type using relational operators. Eg:
 A pointervariable cannot be multiplied by a constant. #include <stdio.h>
 A pointervariable cannot be added to another pointervariable. #include <conio.h>
int main()
Eg: {
#include<stdio.h» double radius, area = 0.0;
Intmain() double *pradius = &radius, *parea = &area;
{ printf ("\n Enter the radius of the circle: ");
char*ch = "Hello World"; scanf("%lf", pradius);
printf("%s",*ch) ; *parea = 3.14 * (*pradius) * (*pradius);
return0; printf("\n The area of the circle with radius %.2lf =%.2lf", *pradius,
} *parea);
o/p: return 0;
Hello World }
o/p:
Eg: Enter the radius of the circle: 7
#include<stdio.h> The area of the circle with radius 7.00 = 153.83
int main()
{

4
int main()
{
Eg: intch, *pch = &ch;
#include <stdio.h> clrscr ();
int main() printf("\n Enter the character:”);
{ scanf(“%c”,&ch);
int num1, num2, num3; printf (“ \n The char entered is: %c ". *pch);
int *pnum1 = &num1, *pnum2 = &num2, printf ("\nASCIIvalueofthechar is: %d", *pch);
*pnum3= &num3; printf(“ \nThecharinuppercaseis:%c",*pch-32);
printf("\n Enter the first number: "); getch();
scanf ("%d", pnuml) : return 0;
printf(“ \n Enter the second number: “); }
scanf ("%d", pnum2); o/p:
printf("\n Enter the third number: "); Enter the character: z
scanf ("%d", pnum3); The char entered is: z
if (*pnum1 > *pnum2 && *pnum1 > *pnum3) ASCII value of the char is: 122
printf (“ \n%d is the largest number ”, *pnurnl); The char in upper case is: Z
if(*pnum2 > *pnum1 && *pnum2 > *pnum3)
printf ( "\n %d is the largestnumber", *pnum2); Eg:
else #include <stdio.h>
printf(“ \n %d isthelargestnumber", *pnum3); #include <conio.h>
return 0; int main()
} {
o/p: charch, *pch
Enter the first number: 5 clrscr();
Enter the second number: 7 printf("\n Enter any character:”);
Enter the third number: 3 scanf("%c", pch);
7 is the largest number if(*pch>='A' && *pch<='Z')
printf ("\n Upper case char was entered");
Eg: else if(*pch>='a' && *pch<='z')
#include <stdio.h> printf (“ \n Lower case char was entered ”);
#include <conio.h> else(*pch>='0' && *pch<='9')

5
printf (“ \n You entered a number"); #include<stdio.h>
getch() ; int main()
return 0; {
} intnum, *pnum = &num, range;
Output int m,*pm=&m;
Enter any character: 7 int n,*pn=&n;
You entered a number int sum = 0, *psum = &sum;
floatavg,*pavg = &avg;
Eg: printf("\n Enter the starting and ending limit of the numbers to be
#include<stdio .h> summed:");
intmain() scanf ("%d %d", pm, pn ) ;
{ range = n – m;
intnum, *pnum = &num; while(*pm <= *pn)
printf("\n Enter any number: "); {
scanf("%d", pnum); *psum = *psum + *pm;
if(*pnum>0 ) *pm = *pm + 1;
printf("\n The number is positive"); }
else printf ("\n Sum of numbers = %d , *psum);
{ *pavg = (float)*psum / range;
if(*pnum<0) printf("\n Average of numbers %.2f",*pavg) ;
printf(“\n The number is negative"); return 0;
else }
printf("\n The number is equal tozero");
} o/p:
return 0; Enter the starting and ending limit of thenumbers to be summed: 0 10
} Sum of numbers = 55
Average of numbers = 5.50
o/p:
Enter any number : -1 Eg:
The number is negative #include <stdio.h>
#include <conio.h>
Eg: int main()

6
{ {
int m, *pm =&m; if (*pnum == 1)
int n, *pn=&n; printf("\n %d is neither prime nor composite", *pnum);
printf("\n Enter the starting and ending limit of the numbers: "); else if(*pnum==2)
scanf ("%d %d", pm, pn); printf ("\n %d is prime", *pnum) ;
while(*pm <= *pn) else
{ for(i=2; i<*pnum/2; i++)
if (*pm %2 == 0) {
printf ("\n %d is even", *pm); if (*pnum/i ==0)
(*pm)++; flag =1;
} }
return 0; if (flag == 0)
} printf ("\n %d is prime", *pnum);
o/p: else
Enter the starting and ending limit of thenumbers: 0 10 printf("\n %d is composite", *pnum);
0 is even }
2 is even printf("\n Enter any number: ");
4 is even scanf ("%d", pnum) ;
6 is even return 0;
8 is even }
10 is even
o/p:
Eg: ***** ENTER -1 TO EXIT *****
#include <stdio.h> Enter any number: 3
int main() 3 is prime
{
intnum, *pnum = &num; 3.12 NULL POINTERS
int i, flag = 0;
printf("\n ***** ENTER -1 TO EXIT *****);  Nullpointer which is a specialpointer that does not point to any value.
printf("\n Enter any number: ");  This means that a null pointer does not point to any valid memory
scanf ("%d", pnum); address.
while(*pnum != -1)

7
 To declare a null pointer you may use the predefined constant int x=10;
NULL, which is defined in several standard header files including charch = 'A';
<stdio.h>,<stdlib.h>and <string.h>. void *gp;
 After including any of these files in your program, write printf("\n Generic pointer points to the integer value = %d",*(int*)gp);
int *ptr = NULL; printf("\nGeneric pointer now points tothecharacter=%c",*(char*)gp) ;
You can always check whether a given pointer variable stores address of return 0;
some variable or contains a NULL by writing: }
if(ptr==NULL) o/p:
{ Generic pointer points to the integer value=10
Statement block; Generic pointer now points to the character = A
}
 You may also initialize a pointer as a null pointerbyusing a constant 0, 3.14 PASSING ARGUMENTS TO FUNCTION USING POINTERS
as shown below.
intptr;  Using call-by-value method, it is impossible to modify the actual
ptr = 0; parameters when you pass them to a function.
 Furthermore, the incoming argumentstoa function are treated as local
3.13 GENERIC POINTERS variables in the functionand those local variables get a copy of the values
passedfrom their calling function.
 A generic pointeris a pointer variable that has void as its data type.  Pointers provide a mechanism to modify data declaredin one function
 The void pointer, or the generic pointer, is a special type of pointer using code written in another function. Inother words: If data is
that can be used to point to variables of any data type. declared in func1( ) and we want to write code in func2() that
 It is declared like a normal pointer variable but using the void keyword modifies the data in funcl(), then we must pass the addresses of the
as the pointer's data type. variables to func2 ().
For eg: void *ptr;  The calling function sends theaddresses of the variables and
 You cannot have a variable of type void,the void pointer will therefore thecalled function must declare thoseincoming arguments as
not point to any data and thus cannot be dereferenced. pointers.
 You need to type cast a void pointer (generic pointer) to another kind of  In order to modify the variablessent by the calling function,
pointer before using it. thecalled function must dereference the pointers that were passed
Eg: toit.
#include<stdio.h>  Thus, passing pointers to afunction avoids the overhead of copying data
int main() from onefunction to another.
{

8
 Hence, to use pointers for passingarguments to a function, the #include<stdio.h>
programmer must do thefollowing: int greater (int *a, int *b, int *c, int *large) ;
• Declare the function parameters as pointers int main()
• Use the dereferenced pointers in the function body {
• Pass the addresses as the actual argument when the function is intnuml, num2, num3, large;
called. printf("\n Enter the first number: ");
scanf("%d", &numl);
Eg: Addition of 2 nos using pointers & functions printf("\n Enter the second number: ");
#include<stdio.h> scanf ("%d", &num2);
#include<conio.h> printf("\n Enter the third number: ");
void sum(int *a, int *b, int *t); scanf ("%d", &num3);
int main() greater(&numl, &num2, &num3, &large);
{ return 0;
intnuml, num2, total; }
printf("\n Enter the first number: "); int greater (int *a , int *b, int *c, int *large)
scanf("%d", &numl); {
printf("\n Enter the second number: "); if(*a > *b && *a > *c)
scanf("%d", &num2); *large = *a;
sum(&numl, &num2, &total); if(*b > *a && *b > *c)
printf ("\n Total = %d", total) ; *large *b;
getch() ; else
return 0; *large = *c;
void sum (int *a, int *b, int *t) printf("\n Largest number = %d", *large) ;
{ }
*t=*a + *b; Output
} Enter the first number: 1
Output: Enter the second number: 7
Enter the first number: 2 Enter the third number: 9
Enter the second number: 3 Largest number =9
Total = 5
Eg: area of circle by passing pointers to functions
Eg: biggest of 3 nos using pointers & functions #include <stdio.h>

9
void read(float *b, float *h); 3.15 POINTERS AND ARRAYS
voidcalculate_area(float *b, float *h, float *a);
int main ()  An array occupies consecutive memory locations.
{  Array notation is a form of pointer notation. The name of the array is the
float base, height, area; starting address of the array in memory. It is also known as the base
read (&base, &height) ; address. In other words, base address is the address of the first
calculate_area(&base, &height, &area); element in the array or the address of arr[0] .
printf ("\n Area of the triangle with base %.1f and height %.1f = %.2f", Eg:
base, height, area) ; main()
return 0; {
} intarr[]={l,2,3,4,5};
void read(float *b, float *h) printf("\n Address of array = %p%p%p", arr,&arr[0],&arr);
{ }
printf("\n Enter the base of the triangle: ”);  One point to notehere is that if x is an integervariable, then x++ adds 1
scanf("%f", b); to thevalue of x.
printf("\n Enter the height of the triangle: ");  But ptr is a pointervariable, so when we write ptr+i, then adding i gives
scanf("%f", h); a pointerthat points i elements further along an array than theoriginal
void calculate area (float *b, float *h, float *a) pointer.
{  Since ++ptr and ptr++ are both equivalent to ptr+1, incrementing a
*a = 0.5 * (*b) * (*h); pointer using the unary ++ operator,increments the address it stores by
} the amount given bysizeof(type) where type is the data type of the
Output variableit points to (i.e., 2 for an integer).
Enter the base of the triangle: 10  When using pointers, an expression like arr[i] is equivalent to writing
Enter the height of the triangle: 5 * (arr+i).
Area of the triangle with base 10.0 and height 5.0 = 25.00  arr]1], i[arr], *(arr+i), *(i+arr) gives the same value.

 Functions usually return only onevaluebut pointers can be used to Eg:


return more than one to the calling function. main()
 This is done by allowing the arguments to be passed by addresses which {
enables the function to alter the values pointed to and thus return more intarrl[ ]={l,2,3,4,5};
than one value. int *ptr, i;
ptr=&arr[2] ;

10
*ptr = -1; }
* (ptr+1) = 0; }
* (ptr-1) = 1; Output
printf(“ \n Array is: ”); 1 2 3 4 5 6 789
for(i=0;i<5;i++)
printf(“%d", *(arr+i) ; Eg:// how to read and print nos by using pointers
Output #include <stdio.h>
Array is: 1 1 -1 0 5 int main()
{
Eg: int i, n ,
main() intarr [10], *parr = arr;
{ printf("\n Enter the number of elements ”);
intarr[ ]={l,2,3,4,5,6,7,8,9}; scanf ("%d", &n);
int *ptr1, *ptr2; printf (“\n Enter the elements: ");
ptr1 = arr; for(i=0; i<n, i++)
ptr2 = ptr1+2; scanf ("%d ", parr+i ),
printf (“%d ", *ptr2-*ptr1); printf ("\n The elements entered are:”);
} for(i=0; i < n; i++)
Output printf("\t %d", *(parr+i));
2 return 0;
}
Eg: Output
#include <stdio.h> Enter the number of elements: 5
main() Enter the elements: 1 2 3 4 5
intarr[]={l,2,3,4,5,6,7,8,9}; The elements entered are: 1 2 3 4 5
int *ptr1, *ptr2;
ptr1 = arr; Eg:// to find the largest nos by using pointers
ptr2 = &arr[8]; #include <stdio.h>
while (ptrl<=ptr2) int main()
{ int i, n , arr(20) ,large=0, pos=0;
printf("%d", *ptr1); int *pn = &n, *parr = arr, *plarge=&large, *ppos = &pos;
ptr1++; clrscr() ;

11
printf("\n Enter the number of elements in the array: "); The position of the largest number in the array is: 4
scanf("%d", pn) ,
for(i=0; i<*pn;i++) 3.16 PASSING AN ARRAY TO A FUNCTION
{
printf(“ \n Enter the number: “);  An array can be passed to a function using pointers.
scanf ("%d", parr+i);  For this, a function that expects an array can declare the formal
} parameter in either of the two following ways:
for(i = 0; i < *pn; i++) func(int arr[ ]); or func(int *arr);
{  When we pass the name of the array to a function, the address of the
if(*(parr+i)> *plarge) zeroth element of the array is copied to the local pointer variable in the
{ function.
*plarge = * (parr+i) ;  unlike ordinary variables the values of the elements are not copied, only
*ppos = i; the address of the first element is copied.
}  When a formal parameter is declared in a function header as an array, it
} is interpreted as a pointer to a variable and not as an array.
printf("\n The numbers you entered are:") ;  With this pointer variable you can access all the elements of the array by
for(i=0; i<*pn;i++) using the expression, array_name + index.
printf("%d",*(parr+i)); func(intarr[],int n); orfunc(int *arr, int n);
printf("\n The largest of these numbers is: %d", *plarge);
printf("\n The position of the largest number in the array is: %d", *ppos); Eg:// to find smallest value in an array in functions by using pointers
return 0; #include<stdio.h>
} voidread_array(int *arr, int n);
Output
voidprint_array(int *arr, int n);
Enter the number of elements in the array: 5
Enter the number: 1 voidfind_small(int *arr, int n , int *small, int *pos);
Enter the number: 2 int main()
Enter the number: 3 {
Enter the number: 4 intnum[10], n , s, pos;
Enter the number: 5 printf("\n Enter the size of the array:");
The numbers you entered are: scanf("%d", &n);
1 2 345
read_array(num, n);
The largest of these numbers is: 5
print_array(num, n);
12
find_small(num, n, &s, &pos); Enter the array elements:
printf("\n The smallest number in the array is %d at position %d", s,pos); 1
return 0; 2
3
} 4
voidread_array(int *arr, int n) 5
The array elements are 1 2 3 4 5
{ The smallest number in the array is 1 at position 4
int i;
printf("\n Enter the array elements:"); 3.17 POINTERS AND STRINGS
for(i=0;i<n;i++)
 In C, strings are treated as arrays of characters that are terminated with a
scanf("%d", &arr[i]);
binary zero character (written as '\0').
}  Consider, for example, char str[10];
voidprint_array(int *arr, int *n) str[0]=Hi;
{ str[1]=’H’;
int i; str[2]=’i’;
printf("\n The array elements are "); str[3]=’\0’;
for (i=0;i<*n; i++)  C language provides two alternate ways of declaring and initializing a
string. First, you may write:
printf("\t %d",*arr[i]);
charstr[10] = {'H', 'i', '!', '\0'};
} charstr[l0] = "Hi!";
voidfind_small(int *arr, int *n, int *s, int *pos)  When the double quotes are used, NULL character (‘\0’) is
{ automatically appended to the end of the string.
for(int i=0;i<*n;i++)  When a string is declared like this, the compiler sets aside a contiguous
{ block of memory 10 bytes long to hold characters and initializes its first
four characters to Hi!\0
if(*(arr+i)< *s)
*s = *(arr+i); Eg:// To print hello world by using pointers
*pos=i; #include<stdio.h>
} int main()
} charstr [] = "Hello" ;
Enter the size of the array:5 char *pstr;

13
pstr = str;
printf("\n The string is: "); Output:
while(*pstr != '\0') Enter the string: How are you
{ Total number of upper case characters =1
printf("%c", *pstr); Total number of lower case characters =8
pstr++;
return 0; Eg://to copy a string to another by using pointers
} #include<stdio.h>
Output: #include<conio.h>
The string is: Hello int main()
{
Eg://to count total no of upper and lower case by using pointers charstr[100] , copy_str[100];
#include<stdio.h> char *pstr, *pcopy_str;
int main() int i = 0;
{ clrscr ();
charstr[100] , *pstr; pstr = str;
int upper = 0, lower = 0; pcopy_str = copy_str;
printf (“ \In Enter the string: "); printf("\n Enter the string: II);
gets(str); gets (str) ;
pstr = str; while(*pstr != '\0')
while(*pstr != '\0') {
{ *pcopy_str = *pstr;
if(*pstr>= 'A' && *pstr<= 'Z') pstr++, pcopy_str++;
upper++; }
else if (*pstr>= 'a' && *pstr<= 'z') *pcopy_str ='\0';
lower++; printf("\n The copied text is:”);
pstr++; pcopy_str = copy_str;
} while(*pcopy_str != '\0')
printf(“ \nTotal number of upper case characters = %d", upper) ; {
printf(“ \nTotal number of lower case characters = %d", lower) ; printf (“%C”, *pcopy_str);
return 0; pcopystr++;
} }

14
getch(); printf(“ \n The copied text is :”);
return 0; puts(copy_str);
} return 0;
}
Output
Enter the string: C Programming Output:
The copied text is: C Programming Enter the string : How are you
Enter the position from which to start : 2
Eg:// to copy a string from a given range by using pointers Enter the number of characters to be copied : 5
#include<stdio.h> The copied text is :w are
int main()
{ Eg:// Reversing a string
charstr[100] , copy_str[100];
char *pstr, *pcopy_str ; #include <stdio.h>
int m, n , i=0; int main()
pstr=str; {
pcopy_str = copy_str; char str[100] ,copy_str[100];
printf("\n Enter the string: “); char *pstr, *pcopy_str;
gets(pstr); pstr = str;
printf("\n Enter the position from which to start: "); pcopy_str = copy_str;
scanf("%d", &m); printf(“\n Enter * to end");
printf("\n Enter the number of characters to be copied:"); printf (“\n Enter the string: ");
scanf("%d", &n); scanf("%c", pstr);
i=0; while (*pstr != ‘*’)
while(*pstr != '\0' &&i < n) {
{ pstr++;
*pcopy_str=*pstr; scanf(“%c”, pstr);
pcopy_str++; }
pstr++; *pstr = '\0' ;
i++; pstr--;
} while (pstr>= str)
*pcopy_str=’\0’; {

15
*pcopy_str = *pstr; while(*pstr1 != '\0')
pcopy_str++; {
pstr--; *pcopy_str = *pstr1;
} pcopy_str++, pstr1++;
*pcopy_str = '\0'; }
printf(“\n The new text is: "); while(*pstr2 != '\0')
pcopy_str = copy_str; {
while(*pcopy_str != '\0') *pcopy_str = *pstr2;
{ pcopy_str++, pstr2++;
printf("%c", *pcopy_str); }
pcopy_str++; *pcopy_str = '\0';
return 0; printf("\n The new text is: ");
} pcopy_str = copy_str;
Output while(*pcopy_str != '\0')
Enter * to end {
Enter the string: Learning C printf("%c", *pcopy_str);
The new text is : C gnintaeL pcopy_str++;
}
Eg:// appending a string using pointers return 0;
#include <stdio.h> }
int main() Output:
{ Enter the first string: Programming in C by
char str1[100] , str2[100] , copy_str[200]; Enter the second string: ReemaThareja
char *pstr1, *pstr2, *pcopy_str; The new text is: Programming in C by ReemaThareja
clrscr() ; ,

Eg: //To count vowels, consonants, whitespaces and digits


pstr1=str1;
pstr2=str2; #include <stdio.h>
pcopy_str = copy_str; int main()
printf("\n Enter the first string: ”); {
gets (str1) ; char line[150];
printf("\n Enter the second string: ”); int i, vowels, consonants, digits, spaces;
gets (str2) ; vowels = consonants = digits = spaces = 0;
printf("Enter a line of string: ");

16
scanf("%[^\n]", line);
Vowels: 1
for(i=0; line[i]!='\0'; ++i)
Consonants: 11
{
Digits: 9
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
White spaces: 2
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' || Sorting of names
line[i]=='U')
{ #include <stdio.h>
++vowels; #include <string.h>
} void main()
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z')) {
{ char name[10][8], tname[10][8], temp[8];
++consonants; int i, j, n;
} printf("Enter the value of n \n");
else if(line[i]>='0' && line[i]<='9') scanf("%d", &n);
{ printf("Enter %d names n \n", n);
++digits; for (i = 0; i < n; i++)
} {
else if (line[i]==' ') scanf("%s", name[i]);
{ strcpy(tname[i], name[i]);
++spaces; }
} for (i = 0; i < n - 1 ; i++)
} {
printf("Vowels: %d",vowels); for (j = i + 1; j < n; j++)
printf("\nConsonants: %d",consonants); {
printf("\nDigits: %d",digits); if (strcmp(name[i], name[j]) > 0)
printf("\nWhite spaces: %d", spaces); {
strcpy(temp, name[i]);
return 0; strcpy(name[i], name[j]);
} strcpy(name[j], temp);
Output: }
Enter a line of string: adfslkj34 34lkj343 34lk }

17
} object program
class project
printf("\n----------------------------------------\n"); program queue
printf("Input NamestSorted names\n"); project stack
printf("------------------------------------------\n"); ------------------------------------------

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


{
printf("%s\t\t%s\n", tname[i], name[i]);
}

printf("------------------------------------------\n");

}
o/p:
Enter the value of n
7
Enter 7 names
heap
stack
queue
object
class
program
project

----------------------------------------
Input Names Sorted names
------------------------------------------
heap class
stack heap
queue object

18

You might also like