Psuc Unit - 5
Psuc Unit - 5
1
Introduction to Pointers
pointer constants,
pointer values,
pointer variables,
accessing variables through pointers,
pointer declaration and definition,
declaration versus redirection,
initialization of pointer variables,
Pointer for inter function communication,
pointer to pointers,
pointer to function.
Arrays and pointers
Pointer arithmetic and arrays,
array of pointers
Strings
Declaration, Initialization,
Input and Output functions,
strings and pointer, 2
Pointers
Objectives
❏ To understand the concept and use of pointers
❏ To be able to declare, define, and initialize pointers
❏ To write programs that access data through pointers
❏ To use pointers as parameters and return types
❏ To understand pointer compatibility, especially regarding pointers to
pointers
3
Derived Types
4
Pointers:
Pointer Constants
Pointer Values
Pointer Variables
5
POINTER CONSTANT
•Each cell can hold one byte of information, has a unique number
associated with it called as ‘address’
• We cannot change them, but we can only use them to store data
values.
6
Pointer constants, drawn from the set of addresses for a
computer, exist by themselves. We cannot change them;
we can only use them.
Pointer Constants
7
POINTER VALUE
int i=10;
10 Variable value
Variable address
3217945756 8
The & Operator:
•The address operator can be used with any variable that can be placed
on the left side of an assignment operator.
9
An address expression(unary expression) consists of an
ampersand (&) and a variable name.
The address operator (&) extracts the address for a variable.
The address operator format is: &variable_name
Pointer Variable
11
Pointer declaration and definition:
General syntax of pointer declaration is,
Data type *pointername;
Data type of a pointer must be same as the data type of a variable to which
the pointer variable is pointing
Examples: int *ip
char *ch
float *fp
double *dp
Pointer initialization:
Pointer Initialization is the process of assigning address of a variable to
pointer variable. Pointer variable contains address of variable of same data type.
int a = 10 ;
int *p;
p=&a
12
Accessing Variables Through Pointers
Dereference Operator(*):
Dereference operator used to give the Value at Address
An indirect expression, one of the expression types in the unary expression category,
is coded with an asterisk (*) and an identifier.
The indirection operator is a unary operator whose operand must be a pointer value.
For example, to access the variable a through the pointer p, we simply code *p
The indirection operator is: *p
p a
Example: 65530 10
int a,*p;
a = 10; 65530
p = &a;
printf("%d",*p); //this will print the value of a.
*p=20; // assign value to variable using pointer
printf("%d",*&a); //this will also print the value of a
The Address and Indirection operators are the inverse of each other.
.
13
// sample program on pointer
p a
#include<stdio.h>
void main() 2214 10
{
int a=10; 65530 2214
int *p;
p=&a;
printf(“%d”,a); //this will print value of a (10)
printf(“%u”,&a); //this will print address of a (2214)
printf(“%u”, p); //this will print value of p (2214)
printf(“value=%d”,*p); // this will print value at address (10)
printf(“%u”,&p); //this will print address of p (65530)
printf(“%d”,*(&a)); // this will also print the value of a (10)
14
// One pointer for many varibles // Many pointers for single varible
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int a=10,b=5,c=20; int a=10,b=5,c=20;
int *p; int *p,*q,*r;
p=&a; p=&a;
printf(“value of a=%d”,*p); printf(“value of a=%d”,*p);
p=&b; q=&a;
printf(“value of b=%d”, *p); printf(“value of a=%d”, *q);
p=&c;
printf(“value of c=%d”,*p); r=&a;
} printf(“value of a=%d”,*r);
}
15
Assign pointer to pointer Function returning pointer
#include<stdio.h> #include<stdio.h>
void main() int * min(int *pa, int *pb);
{ void main()
int a=10; {
int *p,*q,*r; int a,b, *p;
p=&a; printf(“enter a and b”);
printf(“value of a=%d”,*p); scanf(“%d%d”,&a,&b);
q=p; p=min(&a,&b);
printf(“value of a=%d”, *q); printf(“minimum is=%d”,*p);
}
r=p; int * min(int *pa,int *pb)
printf(“value of a=%d”,*r); {
} return(*pa < *pb?pa:pb);
}
16
Accessing Variables Through Pointers
17
Declaration versus Redirection
An asterisk operator can be used in two different contexts:
For declaration and for redirection.
#include<stdio.h>
void main()
{
int a,b,c
int *p,*q,*r;
a=6;b=2;
p=&b;
q=p;
r=&c;
p=&a;
*q=8;
*r=*p;
*r=a+ *q + *(&c);
printf(“%d %d %d” ,a,b,c);
printf(“%d %d %d”,*p,*q,*r));
}
19
Pointer for Inter-function Communication
One of the most useful applications of pointers is in functions, C uses the pass-by-
value for downward communication and the pass-by-address for upward
communication.
#include<stdio.h>
void swap(int*,int*);
main()
{
int a,b;
printf("Enter two numbers");
scanf("%d%d",&a,&b);
printf(“the values before swapping a=%d,b=%d”,a,b);
swap(&a,&b);
printf("The values after swapping a=%d,b=%d",a,b);
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y; 20
*y=temp;
Every time we want a called function to have access to a variable in the
calling function, we pass the address of that variable to the called
function and use the indirection operator to access it.
When several values need to be sent back to the calling function, use
address parameters for all of them. Do not return one value and use
address Parameters for the others.
Note
A void pointer cannot be dereferenced.
21
Pointers to Pointers
Pointer to pointer is pointer variable which stores the address
of another pointer variable.
22
Pointer to Pointer
#include<stdio.h>
void main()
{
int a=10;
int *p1;
int **p2;
p1=&a;
p2=&p1;
printf(“%u”,&a); //this will print address of a (1004)
printf(“%u”, &p1); //this will print address of p1 (1204)
printf(“%u”,&p2); // this will print address of p2(6508)
printf(“%u”,*p2); //this will print value (1004)
printf(“%d”,*p1); // this will also print the value of a (10)
printf(“%d”,**p2); // this will also print the value of a (10)
}
23
Pointer to Pointer
#include<stdio.h>
void main()
{
int a;
int *p; int **q; int ***r;
p=&a; q=&p; r=&q;
printf(“enter number”); //using a
scanf(“%d”,&a);
printf(“Number is:%d”,a)
printf(“enter number”); //using p
scanf(“%d”,p);
printf(“Number is:%d”,a)
printf(“enter number”); //using q
scanf(“%d”,*q);
printf(“Number is:%d”,a)
printf(“enter number”); // using r
scanf(“%d”,**r);
printf(“Number is:%d”,a)
} 24
Demonstrate size of Pointers
#include<stdio.h>
void main()
{
char c,*pc;
int a, *pa;
double x,*px;
printf(“size of c=%d”, sizeof(c));
printf(“size of pc=%d”, sizeof(pc));
printf(“size of starpc=%d”, sizeof(*pc));
printf(“size of a=%d”, sizeof(a));
printf(“size of pa=%d”, sizeof(pa));
printf(“size of starpa=%d”, sizeof(*pa));
printf(“size of x=%d”, sizeof(x));
printf(“size of px=%d”, sizeof(px));
printf(“size of starpx=%d”, sizeof(*px));
}
25
Dereference Type Compatibility
26
Arrays and Pointers
27
same
arr &arr[0]
a is a pointer only to the first element—not the whole array.
29
Array Names as Pointers
30
Multiple Array Pointers
31
Pointer Arithmetic and Arrays
32
Given pointer, p, p ± n is a pointer to the
value n elements away.
Pointer Arithmetic
33
Address of a[i]= Baseaddress+ i*size of element
34
The following expressions are identical.
*(a + n) and a[n]
i[a] or a[i] or *(a+i)
P[0] or 0[a] or
P[1] or 1[a] or
P[2] or 2[a] or
P[3] or 3[a] or
P[4] or 4[a] or
36
Pointers and Relational Operators
Expression Result
Addre
ss Address +
Initial Requi Address
data Oper after Number
Addre red
Type ation Oper
ss Bytes
ation Address –
s Address
Number
int 4000 ++ 4002 2 Address –
Number
Address
int 4000 - - 3998 2
Address + Address = Illegal
char 4000 ++ 4001 1 Address * Address = Illegal
char 4000 - - 3999 1 Address / Address = Illegal
float 4000 ++ 4004 4
Address % Address = Illegal
Address & Address = Illegal
float 4000 - - 3996 4
Address | Address = Illegal
long 4000 ++ 4004 4 Address ^ Address = Illegal
long 4000 - - 3996 4 ~Address = Illegal
37
Accessing one dimensional array using pointer:
38
.
Read and print array using Read and print array using
pointer pointers
#include<stdio.h>6 #include<stdio.h>
void main() #define size 5
{ void main()
int a[12]; {
int i ,n,*p; int a[size];
printf(enter size of array”); int* p ;
scanf(“%d”,&n); printf(“enter values”);
printf(“enter values”); for(p=a;p<a+size;p++)
for(p=a;p<a+n;p++) {
{ scanf(“%d”,p);
scanf(“%d”,p); }
} printf(“array elements are:);
printf(“array elements are:); for(p=a;p<a+size;p++)
for(p=a;p<a+n;p++) {
{ printf(“%3d”,*p);
printf(“%3d”,*p); }
} }
} 39
#include<stdio.h>
void main()
{
int a[15];
int *min,n;
printf(“enter size of array”);
scanf(“%d”,&n);
printf(“enter values”);
for(p=a;p<a+n;p++)
{
scanf(“%d”,p);
}
min=a;
for(p=a+1;p<a+n;p++)
{
if(*p <*min)
*min=*p;
}
printf(“minimum=%3d”,*min);
}
40
Passing an Array to a Function
Now that we have discovered that the name of an array
is actually a pointer to the first element, we can send the
array name to a function for processing. When we pass
the array, we do not use the address operator.
41
Passing an Array to a Function
int main()
{
#include<stdio.h> int a[15];
void multiply(int *pa, int n) int *i, n;
{ printf(“enter n”);
int *j; scanf(“%d”,&n);
for(j=pa; j<pa+n ;j++) printf(“enter array elements”);
*j=*j * 2; for(i=a; i< a+n; i++)
} scanf("%d", i); }
multiply(a, n) ;
printf(" Doubled value is:\n");
For(i=a; i<(a+n);i++)
{ printf("%2d", *i); }
return 0;
}
42
Pointers and two dimensional arrays:
Let us consider a two dimensional array A[i][j] then array elements can be
accessed through pointer index notation using *(*(A + i) + j)
For example:
void main()
{
int A[3][4]={2,11,24,42,31,19,72,4,6,9,1,5};
printf(“Array elements are\n”);
for(i =0; i < 3; i++)
{
for(j =0; j < 4; j++)
{
printf(“%d”, *(*(A + i) + j));
}
}
void main ()
{
int var[] = {10, 100, 200};
int i, *ptr[3];
for ( i = 0; i < 3; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < 3; i++)
{ printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
}
44
C Strings
A C string is a variable-length array of characters that
is delimited by the null character.
45
Storing Strings and Characters
46
Differences Between Strings and Character Arrays
47
String Literal References
48
DECLARING AND INITIALIZING STRING VARIABLES
Declaring a String:
A string variable is a valid C variable name and always declared
as an array.
1. char str1[7]=“Welcome”;
2. char str2[8]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’,’\0’};
Without size:
3. char str[]=“welcome”;
50
Memory for strings must be allocated before the
string can be used.
Defining Strings
51
Accessing Strings using pointer
void main()
{
char s[15],r[15];
char *sp,*rp
printf("Enter a String : ");
gets(s);
sp=&s[2];
rp=s;
printf(“ String : %s\n pointer=%s",s,sp);
printf(“\n %c“,*sp);
printf(“enter string”)
scanf(“%s”,rp);
printf(“%s”,s);
}
String Input/Output Functions
C provides two basic ways to read and write strings.
53
STRING INPUT/OUTPUT FUNCTIONS(Contd…)
The string can be read using the scanf function with the format specifier %s.
Syntax for reading string using scanf function is
scanf(“%s”, string_name);
Disadvantages:
The termination of reading of data through scanf function occurs, after finding
first white space through keyboard. White space may be new line (\n), blank
character, tab(\t).
For example if the input string through keyword is “hello world” then only
“hello” is stored in the specified string.
54
STRING INPUT/OUTPUT FUNCTIONS(Contd…)
NOTE:
If the string to be printed is larger than the field width w, the entire string will
be printed.
If the string to be printed is smaller than the field width w, then appropriate
numbers of blank spaces are padded at the beginning of the string so as to
ensure that field width w is reached.
55
STRING INPUT/OUTPUT FUNCTIONS(Contd…)
Precision Specifier:
Syntax: %w.ns
Here, w is the specified field width, n indicates that first n characters have to
be displayed and s indicates that the string is being used.
Left justification:
Syntax: %-w.ns
Here, - just before w indicates that string is printed using left justification.
w is the field with and s indicates that the string is being printed.
56
include<stdio.h>
void main()
{
char s[20],s1[20]; Output:
printf("enter string"); Enter string welcome
scanf("%s",s);
printf(‘enter another string”);
Enter another string
scanf(“%s”,s1); snistengclg
printf("%s",s);
printf("%2s",s); welcome
printf("%10s",s); welcome
printf("%-10s",s); welcome
printf("%-10.5s",s); welcome
printf(%15.2s”,s1); welco
printf(%-15.2s”,s1); sn
} sn
57
Character I/O from keyboard:
To read characters from the keyboard and write to the screen, it takes the
following form:
char c = getchar( ); //reads one character from the keyboard
putchar(c); // display the character on the monitor
The function accepts string from the keyboard. The string entered includes the
white spaces. The input will terminate only after pressing <Enter Key>.
Once the <Enter key > is pressed, a null character(\0) appended at the end of
the string.
Advantage: It is capable of reading multiple words from the keyword.
return 0;
} 60
//Write a program to count the number of letters, words, and lines in a
given text.
#include<stdio.h>
void main() {
int noc=0,nol=0,now=0,nos=0;
char ch;
printf(“enter string\n”);
while((ch=getchar())!=EOF) {
if(ch==‘ ‘)
{
nos++; now++;
}
else if(ch==‘\n’)
{
nol++; now++;
}
else
noc++; }
printf("\n Number of character=%d",noc);
printf("\n Number of line=%d",nol);
printf("\n Number of words=%d",now);
printf("\n Number of space=%d",nos); }
Write a c program to check given string is a palindrome or not
#include <stdio.h>
#include <string.h>
void main()
{
char str[25];
int i, n, f =1,j;
printf("Enter a string \n");
gets(str);
n=strlen(str);
printf("The length of the string %s is %d\n", str, n);
for (i=0,j=n-1; i<=n/2 ; i++,j--)
{
if (str[i] != str[j])
{ f = 0;
break;
}
}
if (f == 1)
printf ("%s is a palindrome \n", str);
else
printf("%s is not a palindrome \n", str);
} 62
String Manipulation Functions
The C Library provides a rich set of string handling functions that are placed
under the header file <string.h> and <ctype.h>.
63
STRING HANDLING FUNCTIONS(Contd…)
strlen () function:
This function counts and returns the number of characters in a string. It takes
the form
Syantax: int n=strlen(string);
Where n is an integer variable, which receives the value of the length of the
string. The counting ends at the first null character.
64
STRING HANDLING FUNCTIONS(Contd…)
strcat () function:
It does so by removing the null character at the end of string1 and placing
string2 from there.
strcat function may also append a string constant to a string variable. The
following is valid.
strcat(part1,”Good”);
66
STRING HANDLING FUNCTIONS(Contd…)
strcmp () function:
The strcmp function compares two strings, it returns the value 0 if they are
equal.
If they are not equal, it returns the numeric difference between the first non
matching characters in the strings.
68
STRING HANDLING FUNCTIONS(Contd…)
70
Always use strncpy to copy one string to another.
String-number Copy
71
STRING HANDLING FUNCTIONS(Contd…)
strstr () function:
It is a two-parameter function that can be used to locate a sub-string in a string.
It takes the form:
strstr (s1, s2);
strchr() function:
It is used to determine the existence of a character in a string.
Example: strchr (s1,’m’); //It locates the first occurrence of the character ‘m’.
Example: strrchr(s2,’m’); //It locates the last occurrence of the character ‘m’.
72
String in String
73
Character in String (strchr)
74
The basic string span function, strspn, searches the string, spanning characters
that are in the set and stopping at the first character that is not in the set.
They return the number of characters that matched those in the set.
The second function, strcspn, is string complement span; its functions stop
at the first character that matches one of the characters in the set.
int strcspn(const char* str, const char* ste);
#include <stdio.h>
#include <string.h>
int main ()
{ int len;
char str1[] = "ABCDEFG019874";
char str2[] = "ABCD";
len = strspn(str1, str2);
printf("Length of initial segment matching %d\n", len );
return(0); }
String Span
76
/*Define functions- length of a string, copy, concatenate, convert into uppercase
letters, compare two strings for alphabetical order- over strings and implement
in a program*/
#include<stdio.h>
#include<string.h>
void main() {
char str1[15],str2[15],str3[20];
int n,c,len,i,cn;
char *p;
printf("\n Enter the string1 ");
gets(str1);
puts(str1);
printf("\n Enter the string2 ");
scanf("%s",str2);
printf("%s",str2);
printf("\nMENU");
printf("\n 1. String Length 2. String Copy 3. String Concatenation");
printf("4. String Comparison 5.Reverse of string 6 .Search substring 7.strspn");
printf("\n Enter the choice u want to perform");
switch(n)
{
case 1: len=strlen(str1);
printf("\n The length of the string entered is %d",len);
break;
case 2: strcpy(str1,str2);
printf("\n 1st string =%s,2nd string=%s\n",str1,str2);
break;
case 3: strcat(str1,str2);
printf("\n after concatenation string1=%s and string2=%s",str1,str2);
break;
case 4: c=strcmp(str1,str2);
if(c==0)
printf("\n Both are equal");
else
printf("\n Both are different");
break;
case 5: printf("\reverse string is: %s",strrev(str1));
break;
case 6: p=strstr(str1,”is”);
if (p==NULL)
printf(“substing not found”);
else
printf(“substring found at %d location”,p-str1);
break;
case 7: cn=strspn(str1,”aeioucn”)
printf(“strspn=%d”,cn);
cn =strcspn(str1,”teib”);
printf(“strcspn=%d”,cn);
default: printf("\n Enter correct choice");
}
}
Arrays of Strings
Another common application of two dimensional arrays is to store an
array of strings
A string is an array of characters; so, an array of strings is an array of arrays of
characters
char names[MAX][SIZE];
int main()
{
char colour[4][10] = {"Blue", "Red", "Orange", "Yellow"};
for (int i = 0; i < 4; i++)
puts(colour[i]);
return 0;
}
80