ICP-PART-8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 146

Introduction to Computers and

Programming (CSE 101)


Dr. Ruhul Amin,
Asst. prof., CSE

ICP-PART-8
About strings
 Representation in C
 String Literals
 String Variables
 String Input/Output
– printf, scanf, gets, puts
 String Functions
– strlen, strcpy, strncpy, strcmp, strncmp, strcat,
strncat, strchr, strrchr, strstr, strspn, strcspn, strtok
Introduction
 A string is an array of characters.
– Individual characters are stored in memory in ASCII
code.
 A string is represented as a sequence of characters
terminated by the null (‘\0’) character.

 Null character is also named as string-termination


character.
 Internally, the string is nothing but an array of individual
String Literals
 String literal values are represented by
sequences of characters between double
quotes (“)
 Examples
– “” represents empty string
– “hello”
 “a” versus ‘a’
– ‘a’ is a single character value (stored in 1 byte) as
the ASCII value for the letter, a
– “a” is an array with two characters, the rst is a, the
De ning String Variables
 A string is declared like any other array
 Except that its data type is speci ed as character
Syntax: char string-name [size];
 Size determines the number of characters in string_name.
 When a character string is assigned to a character array,
it automatically appends the null
 character (‘\0’) at the end of the string.
– size should be equal to the number of characters in
the string plus one.
Examples
 char name[30];
 char city[15];
 char dob[11];
 A string may be initialized at the time of
declaration.
Null character
 Important issues in handling the strings is null
character
 Null character is used to terminate the string
 Char name[10]=“IIITNR”

I I I T N R \0


[0The] null
[1] character
[2] [3]is not
[4] counted
[5] [6] towards[10]the length of
the strings, but takes memory of one element
 Null character cannot be read or written but it is used
internally only
Reading and Writing a String
 A string can be read and written by using
single scanf and printf function
 %s(string)
 No loop is needed
Example:
char name[30];
::
scanf (“%s”, name);
Contd.
 The ampersand (&) is not required before the variable
name with “%s”.
– “name” represents an address.
 The scanf function reads a string from the keyboard till a
whitespace character(blank,tab,newline) is encountered.
 After reading is complete, the null character is appended
automatically at the next position inside the array.
 scanf (“%s”, name);
 If we type “IIIT NR”
 name will be assigned the string “IIIT”
Contd..
 If we are interested to read a string consisting of blank
character as well as, we want to read a line of text.
 gets() function is used
 string.h header le must be included to use gets()
 Similarly for printing a string puts function can be used.
Syntax:
gets(string name)
puts(string)
Contd.

 Size of is 5 bytes and len is 4


Example:
#include<stdio.h>
#include<string.h>
main()
{
Char str[30]
printf(“ eneter a line of text”);
gets(str);
puts(“the entered line is”)
puts(str);
}
Reading a line :: Alternate Approach
Copy one string into another and
count the number of character
main() Not allowed Gives error
{ (Incomputable types in assignment )
char str1[20],str2[20]; char str1[10]=“hellow”;
int i; char str2[10];
printf(“enter the string”); str2=str1;
scanf(“%s”,str1);  Once the string is initialized, it can
for(i=0;str1[i]!=‘\0’;i++) not be assigned to another set of
str2[i]=str1[i]; characters
str2[i]=‘\0’;
printf(“%s”,str2);
printf(“Number of characters %d”,i);
}
Processing Character Strings
 There exists a set of C library functions for
character string manipulation.
– strcpy :: string copy
– strlen :: string length
– strcmp :: string comparison
– strtcat :: string concatenation
 It is required to add the line #include <string.h>
strcpy()
 strcpy(dest,src): copies one string into another
 Assigns the contents of src to dest.
 Returns address of the destination string.
strcpy()
String copy without strcpy()
strlen()
 Counts and returns the number of characters in a
string.
Syntax: int strlen (str);
Example:
 len=strlen (string); /* Returns an integer */
– The null character (‘\0’) at the end is not counted.
– Counting ends at the rst null character.
Example:
char city[15];
int n;
strcpy (city, “NAYARAIPUR”);
Count total character without strlen
Count total character without strlen
#include <stdio.h>
int main()
{
char s[] = "Programming is fun";
int i=0,count=0;
while(s[i] != '\0’)
{
count++;
i++;
}
printf("Length of the string: %d", count);
return 0;
}
Strcmp()
Compares two character strings.
int strcmp(char *str1, char *str2);
– Compares the two strings and returns 0 if they are
identical; non-zero otherwise.
Examples:
 if (strcmp(city, “Delhi”) == 0)
 { …… }
 if (strcmp(city1, city2) != 0)
 { …… }
Contd..
 Actually, the function returns the di erence in
ASCII values of the rst letter of mismatch.
 Less than 0
– If the ASCII value of the character they di er at is
smaller for str1, or str2 is longer than str1
 Greater than 0
– If the ASCII value of the character they di er at is
greater for str1, or str1 is longer than str2
 Equal to 0
– If the two strings are identical
String Comparison
strcmp examples:
 strcmp(“hello”,”hello”) -- returns 0
 strcmp(“yello”,”hello”) -- returns value > 0
 strcmp(“Hello”,”hello”) -- returns value < 0
String Comparison: Program Example

strcmp(str1, str2) = 32 strcmp(str1, str3) = 0


The rst unmatched character between string str1 and str2 is third
character. The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67.
Hence, when strings str1 and str2 are compared, the return value is 32.
strcat()
 Joins or concatenates two strings together.
 char strcat (char str1, char str2);
– str2 is appended to the end of str1.
– The null character at the end of str1 is removed, and
str2 is joined at that point.
String library function
strncpy(dest,src,n) Copies up to n characters from src to dest string
strncmp(str1,str2,n) Compare str1 and str2 looking at no more than n
characters
strsmpi(str1,atr2) Compare str1 and str2 ignoring the case sensitivity
Strlwr(str1) Converts string str1 to all lower case & returns a
pointers
Strupr(str1) Converts string str1 to all upper case & returns a
pointers
memcpy(dest,src,n) Copies a block of n bytes of strings str1 and str2
memcmp(dest,src,n) Compares rst n bytes of strings str1 and str2
strchar(str1,ch) Scans the string str1 for the rst occurrences of
character ch
Strmset(str1,ch,n) Sets rst n character in the string str1 to the character
test
#include <stdio.h>
int main(void)
{
char str[15]={'H','E','L', 'L',‘O','\0','W’};
printf("%s",str);
}
Output:
HELLO
Program to count vowels, consonants,
digits
main(){
char line[150];int i, vowels=0, consonants=0, digits=0, spaces=0;
printf("Enter a line of string: ");
scanf("%[^\n]", line);
for(i=0; line[i]!='\0'; ++i){
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A'
|| line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U'){++vowels;}
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z')){++consonants;}
else if(line[i]>='0' && line[i]<='9'){++digits;}
else (line[i]==' ') {++spaces;}}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
Check for given string is PALINDROME
#include<stdio.h>
#include<string.h>
main() {
char a[10];
int i,len, ag=0;
printf("\nENTER A STRING: ");
gets(a);
len=strlen(a);
for (i=0;i<len;i++) {
if(a[i]==a[len-i-1])
ag= ag+1;
}if( ag==len) printf("\nTHE STRING IS PALINDROM");
else printf("\nTHE STRING IS NOT PALINDROM");}
Passing string to a Function
Pointers-Analogy
Analogy-1
 To look up a speci c topic in a book so you open it and nd the
index.
– The index says the glossary is on page 200.

Analogy-2
 If I take you to a parking lot and ask you to nd me a red car, you
extend one nger (of your choice ;)) and point to a red car.
– Your nger is not the answer. Your nger tells me nothing, but if
I look where you're nger is pointing to, I can nd what I was
looking for.
– Now I can ask you to nd a blue car and you can redirect your
nger (reassign) it to a new car. Now your pointer (the same one
Example
Pointers in C-Introduction
 A pointer is a variable that represents the
location (rather than the value) of a data item.
 They have a number of useful applications.
– Enables us to access a variable that is de ned outside
the function.
– Can be used to pass information back and forth
between a function and its reference point.
– More e cient in handling data tables.
– Reduces the length and complexity of a program.
– Sometimes also increases the execution speed.
Basic Concept
 In memory, every stored data item occupies one
or more contiguous memory cells(bytes).
– The number of bytes required to store a data item
depends on its type (char, int, oat, double, etc.).
 Whenever we declare a variable, the system
allocates memory location(s) to hold the value of
the variable.
– Since every byte in memory has a unique address, this
location will also have its own (unique) address.
Contd.
 Consider the statement
– int xyz = 50;
 This statement instructs the compiler to allocate
a location for the integer variable xyz, and put
the value 50 in that location.
 Suppose that the address location chosen is
1380.
 xyz =variable
 50 =value
 1380 =address
Contd.
 During execution of the program, the system
always associates the name xyz with the
address 1380.
– The value 50 can be accessed by using either the
name xyz or the address 1380.
 Since memory addresses are simply numbers,
they can be assigned to some variables which
can be stored in memory.
– Such variables that hold memory addresses are
called pointers.
– Since a pointer is a variable, its value is also stored
Contd.
 Suppose we assign the address of xyz to a
“pointer” variable p.
– p is said to point to the variable xyz.

p = &xyz;
Address vs. Value
 Each memory cell has an address associated with it.
 Each cell also stores some value.
 Don’t confuse the address referring to a memory location
with the value stored in that location.

 Variables name memory locations, which hold values.


Accessing the Address of a Variable
 The address of a variable can be determined using the ‘&’ operator.
– The operator ‘&’ immediately preceding a variable returns the
address of the variable.
 Example:
– p = &xyz;
– The address of xyz (1380) is assigned to p.
 The ‘&’ operator can be used only with a simple variable or an
array element.
– &distance
– &x[0]
– &x[i-2]
Contd.
 Following usages are illegal:
– &235 -- Pointing at a constant.
– int arr[20];
– :
– &arr; -- Pointing at array name.
– &(a+b) -- Pointing at expression.
Important points on Pointers
 Normal variable stores the value whereas pointer variable stores the
address of the variable.
 The content of the C pointer always be a whole number i.e. address.

 & symbol is used to get the address of the variable.

 * symbol is used to get the value of the variable that the pointer is
pointing to.
 If pointer is assigned to NULL, it means it is pointing to nothing.

 Two pointers can be subtracted to know how many elements are


available between these two pointers.
 But, Pointer addition, multiplication, division are not allowed.
Pointer Declarations
 Pointer variables must be declared before we
use them.
General form:
data_type *pointer_name;
 Three things are speci ed in the above
declaration:
– The asterisk (*) tells that the variable
– pointer_name is a pointer variable.
– pointer_name needs a memory location.
– pointer_name points to a variable of type data_type.
Example:
 int *count;
 oat *speed;
 Once a pointer variable has been declared, it
can be made to point to a variable using an
assignment statement like:
 int *p, xyz;
 p = &xyz;
– This is called pointer initialization.
Contd..
Things to Remember
 Pointer variables must always point to a data item of the
same type.

 Assigning an absolute address to a pointer variable is


prohibited
Example-1
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
ptr = &q; /* address of q is assigned to ptr
*/
printf("%d", *ptr); /* display q's value using ptr variable
*/
return 0;
}
Addition of two numbers using
pointer
Swap of two numbers using pointer
Example 3
examples
main()
{ int a; int *p;
p=&a;
printf(“%d”, p);
} Output: print
address of a
Contd.
main() main()
{ int a; int *p; { int a=10; int *p;
p=&a; p=&a;
printf(“%d”, p); printf(“%d”, a);
printf(“%d”, *p); *p=12;
Output: print printf(“%d”, a);
address of a Output: a=10
Garbage a =12
value of a is
Example -3
int main(){
int* pc;
int c; c=22;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
c=11;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
*pc=2;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
}
Example 4
Contd.
Contd.
Pointers and Arrays
 When an array is declared
– The compiler allocates a base address and su cient
amount of storage to contain all the elements of the
array in contiguous memory locations.
– The base address is the location of the rst element
(index 0) of the array.
– The compiler also de nes the array name as a
constant pointer to the rst element
Contd.
 Consider the declaration:
– int x[5] = {1, 2, 3, 4, 5};
 Suppose that the base address of x is 2500,
and each integer requires 4 bytes.
Contd.
 Both x and &x[0] have the value 2500.
p = x; and p = &x[0]; are equivalent.
 Access a successive values of x by using p++ or
p-- to move from one element to another.
 Relationship between p and x:
Pointers with Arrays
 Array names essentially are pointers.
Array elements are stored in contiguous
int arr[3]
(consecutive) locations in memory.
For example: int a[10];
 a is a pointer to the rst element of the array.
 That is, *a is the same as a[0].
 a+i is a pointer to a[i].
*(arr+i), is equal to arr[i].
Pointers with Arrays
 Consider int *ip, z[5]
 ip = &z[0];
 This sets our pointer to point at the rst element of the array
– In fact, z is a pointer as well and we can access z[0] either using
z[0], *ip, or *z
 What about accessing z[1]?
– We can do z[1] as usual, or we can add 1 to the location pointed
to by ip or z, that is *(ip+1) or *(z+1)
– While we can reset ip to be ip = ip+1, we cannot reset z to be z =
z+1
– adding 1 to ip will point to z[1], but if z = z + 1 were legal, we
would lose access to the rst array location since z is our array
variable
Pointers with Arrays
Notice that ip=ip+1 (or ip++) moves the pointer 4 bytes
instead of 1 to point at the next array location

– The amounted added to the pointer is based on the size of the


array element
 8 for an array of doubles
 1 for an array of chars (strings)
 4 for an array of ints
Iterating Through the Array
 Here we see two ways to iterate through an array, the
usual way, but also a method using pointer arithmetic
int j;  int *pj;
for(j = 0; j < n; j++)  for(pj = a; pj < a + n; pj++)
 a[j]++;  (*pj)++;
 Let’s consider the code on the right:
– pj is a pointer to an int
– We start with pj pointing at a, that is, pj points to a[0]
Iterating Through the Array
– The loop iterates while pj < a + n
 pj is a pointer, so it is an address
 a is a pointer to the beginning of an array of n elements so a + n
is the size of the array
 pj++ increments the pointer to point at the next element in the
array
 The instruction (*pj)++ says “take what pj points to and
increment it”
– NOTE: (*pj)++; increments what pj points to, *(pj++); increments the
pointer to point at the next array element
 what do each of these do? *pj++; ++*pj;
Array Example using Pointer
int x[4] = {12, 20, 39, 43}, *y;
y = &x[0]; // y points to the beginning of the array
printf("%d\n", x[0]); // outputs 12
printf("%d\n", *y); // also outputs 12
printf("%d\n", *y+1);// outputs 13 (12 + 1)
printf("%d\n", (*y)+1); // also outputs 13
printf("%d\n", *(y+1)); // outputs x[1] or 20
y+=2; // y now points to x[2]
printf("%d\n", *y); // prints out 39
*y = 38; // changes x[2] to 38
printf("%d\n", *y-1); // prints out x[2] - 1 or 37
*y++; // sets y to point at the next array element
printf("%d\n", *y); // outputs x[3] (43)
(*y)++; // sets what y points to to be 1 greater
printf("%d\n", *y); // outputs the new value of x[3] (44)
A simple example to print the address
of array elements
#include <stdio.h>
int main( )
{
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
/* for loop to print value and address of each element of array*/
for ( int i = 0 ; i < 7 ; i++ )
{
printf("val[%d]: value is %d and address is %d\n", i, val[i], &val[i]);
}
return 0;
}
Example to print the address of array
elements using Pointer
#include <stdio.h>
int main( )
{
int *p;
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = &val[0];
for ( int i = 0 ; i<7 ; i++ )
{
printf("val[%d]: value is %d and address is %p\n", i, *p, p);
p++;
}
return 0;
}
Pointer Increment on array elements
#include <stdio.h>
int main( )
{
int *p;
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = val;
for ( int i = 0 ; i<7 ; i++ )
{
printf("val[%d]: value is %d and address is %p\n", i, *(p+i), (p+i));
}
return 0;
}
Example: Output?
#include <stdio.h>
int main() {
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
// ptr is assigned the address of the third element
ptr = &x[2];
printf("*ptr = %d \n", *ptr);
printf("*(ptr+1) = %d \n", *(ptr+1));
printf("*(ptr-1) = %d", *(ptr-1));
return 0;
}
Pointer Increment on array elements
3,4,2
Pointer increment and scale factor
 An integer value can be added to or subtracted from a
pointer variable.

 In reality, it is not the integer value which is added/


subtracted, but rather the scale factor times the value.
Contd.
Data type Scale factor
Char 1
Int 2
oat 4
double 8
 If p1 is an integer pointer, then p1++
 will increment the value of p1 by 4.
Example on pointers with arrays:
Output?
main () {
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p; int i;
p = balance;
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) );
}
Output
Example on pointers with arrays:
Output?
Write a program in C to compute the sum of all elements in an array
using pointers
Rules of pointer operations
The following rules apply when preforming operations on
pointer variables
 A pointer variable can be assigned the address of another
variable (pv=&v)
 A pointer variable can be assigned the values of another
pointer variable (pv=px)
 A pointer variable can be initialized with NULL or Zero value
 A pointer variable can be pre- xed or post xed with
increment or decrement operators
 An integer value may be added or subtracted from a
pointer variable (pv+3, ++pv)
Contd.
 When two pointers point to the same array, one
pointer variable can be subtracted from another
 When two pointers point to the objects of the same
data types, they can be compared using relational
operators
 A pointer variable cannot multiplied by a constant
 Two pointer variable cannot be added
 A value cannot be assigned to an arbitrary
address(&x=10 is illegal)
Pointer Arithmetic
 Like any other variables pointer variables can be
used in expressions
 Every time pointer is incremented, it points to the
immediate next location of its type
Pointer Arithmetic

 printf(“%d%d%d”, *(num+1), *(num+2), *(num+3));


Example-2:
char str[]=“BANTI is a nice girl”;
char *ptr=str+6;
printf(“%s”, ptr);
Unary Pointer Arithmetic Operators
 variable++: Adds sizeof(datatype) number of bytes to
pointer, so that it points to the next entry of the datatype.
 variable −−: Subtracts sizeof(datatype) number of bytes
to pointer, so that it points to the next entry of the
datatype.
 Example:
int main(){
int *ptrn;
long *ptrlng;
ptrn++; //increments by sizeof(int) (4 bytes)
ptrlng++; //increments by sizeof(long) (8 bytes)
}
Pointer Expressions
 Like other variables, pointer variables can be
used in expressions.
 If p1 and p2 are two pointers, the following
statements are valid:
– sum = *p1 + *p2;
– prod = *p1 * *p2;
– prod = (*p1) * (*p2);
– *p1 = *p1 + 2;
– x = *p1 / *p2 + 5;
Program using pointer expressions
main() {
Int a,b,*p1,*p2,x,y,z;
a=12;b=4;p1=&a;p2=&b;
Output:
x=*p1* *p2-6; Address a=1000
y= 4*-*p2/*p1+10; Address b=2000
printf(“Addrsss a=%u”,p1);
printf(“Addrsss b=%u”,p2); a=12 b=4
printf(“a=%d,b=%d”,a,b); x=42, y=9
printf(“x=%d,y=%d”,x,y);
*p2=*p2+3; *p1=*p2-5; z=*p1 * *p2-6;
A=2,b=7,z=8
printf(“a=%d,b=%d”,a,b);
printf(“z=%d”,z);
(4*(-(*p2)))/((*p1))+10
Passing Pointers to a Function
 Pointers are often passed to a function as
arguments.
–Allows data items within the calling program to be
accessed by the function, altered, and then returned
to the calling program in altered form.
 Called call-by-reference (or by address or by location).
 Normally, arguments are passed to a function by value.
(Call-by value)
– The data items are copied to the function.
– Changes are not re ected in the calling program.
passing arguments by value
passing arguments by
reference
Contd.
Call by value Call by reference
A copy of value is passed to the An address of value is passed to
function the function
Changes made inside the Changes made inside the
function is not re ected on other function is re ected outside the
functions function also
Actual and formal arguments Actual and formal arguments
will be created in di erent will be created in same memory
memory location location
Contd..
-5Test
Null Pointer
 Sometimes we want a pointer that points to
nothing.
 In other words, we declare a pointer, but we’re
not ready to actually point to something yet.
 int *p; p = NULL; /* p is a null pointer */
Double pointer
int x=5;
int *p;
p=&x;
*p=6;
int **q;
q=&p;
Double pointer
Double pointer
main() {
int i =50;
int **ptr1;
int *ptr2;
ptr2 = &i;
ptr1 = &ptr2;
printf("\nThe value of **ptr1 : %d",**ptr1);
printf("\nThe value of *ptr2 : %d",*ptr2);
}
Double pointer
Memory representation
Memory representation
Memory representation
Memory representation
Memory representation
Output
1 1 206
2 2 300
2 3 409
2 3 410
Function Pointers
 A function pointer is a pointer that holds the address of a function.
 The ability of pointers to point to functions turns out to be an
important and useful feature of C.
Declaring Function Pointers:
void (*foo)();
 Declare a pointer to a function that is passed void and returns void.
 The parentheses make it a function pointer with a name of foo.
Contd..
Example:
 int (*f1)(double); // Passed a double and returns
an int //
 void (*f2)(char*); // Passed a pointer to char and returns
void
 double* (*f3)(int, int); // Passed two integers and
returns a pointer to a double//
 int *f4(); // f4 as a function that returns a pointer to an
integer
 int (*f5)(); //f5 is a function pointer that returns an
integer.
Example:
void func1(); void func2(); void func1(){
int main() { printf("TEST1");
//declaring function pointers// }
void(*p1)();
void(*p2)();//assigning address of void func2(){
function pointer printf("TEST2");
p1=func1; }
p2=func2;// calling function through
pointers
p1(); Output:
(*p1)();
p2();(*p2)(); TEST1 TEST1 TEST2 TEST2
return 0; }
Example 2
int add(int a, int b)
{
return a+b;
}
int main()
{
int c;
int (*p)(int, int)
p=&add; // Equal(p=add)
c=(*p)(2,3); // Equal(p(2,3)) //deference and executing function
printf(“%d”,c);
}
Example-3
void add(int x, int y) { if (c == 0)
printf("%d", x+y);} add(a,b);
void subtract(int x, int y) if (c == 1)
{ subtract(a,b);
printf("%d", x-y);} if (c == 2)
void multiply(int x, int y) multiply(a,b);
{ return 0;
printf("%d", x*y);} }
int main(){
int c, a = 15, b = 10;
printf("(0) Add, (1) Subtract, (2) Multiply");
scanf("%d", &c);
Example-3 using function pointer
void add(int x, int y) int main()
{ {
printf("%d", x+y); void (*pArr[])(int, int) = {add,
} subtract, multiply};
void subtract(int x, int y) int c, a = 15, b = 10;
{ printf("(0) Add, (1) Subtract, (2)
printf("%d", x-y); Multiply");
} scanf("%d", &c);
void multiply(int x, int y) (*pArr[c])(a, b);
{ return 0;
printf("%d", x*y);
}
void pointer in C
 Ex:-
char *ptr;
int var1;
ptr=&var1; //This is invalid because ‘ptr’ is a character pointer
variable.
 A void pointer is nothing but a pointer variable declared
using the reserved word in C ‘void’.
 Ex:- void *ptr; // Now ptr is a general purpose pointer
variable
 Address of any variable of any data type (char, int, oat
etc.)can be assigned to a void pointer variable.
Contd.
Ex-2: void *v;
int *i;
int a = 10; int ivar;
char b = 'x'; char chvar;
 void *p = &a; // void oat fvar;
pointer holds address v = &ivar; // valid
v = &chvar; //valid
of int 'a' v = &fvar; // valid
 p = &b; // void pointer i = &ivar; //valid
holds address of char i = &chvar; //invalid
'b i = &fvar; //invalid
Pointers and Dynamic
memory allocation
int total;
int square(int x){
return x*x;}
int squareofsum(int x,int y){
int z=square(x+y);
return z;}
int main(void) {
int a=4,b=8;
total=squareofsum(a,b);
printf("%d",total);
}
Limitations of stack memory
 Stack over ow because of bad recursion
 The memory set aside for stack does not
grow dynamically during run time.
 if we want to declare are large size, need
to declare as a local variable, then we need
to know the size of array at compile time.
Solution is HEAP
 Heap can grow as long you need.
 Heap is large pool of memory available
to programmer.
Dynamic Memory Allocation
 Many a time we face situations where data are dynamic in nature.
– Amount of data cannot be predicted be forehand.
– Number of data items keeps changing during program
execution.
 Such situations can be handled more easily and e ectively using
dynamic memory management techniques.
 Much of the power of pointers stems from their ability to track
dynamically allocated memory.
 The management of this memory through pointers forms the basis
for many operations, including those used to manipulate complex
data structures.
 The ability to allocate and then deallocate memory allows an
Example:
int main()
{
int n;
printf(“Ente sizeof array”);
Scanf(“%d”, &n);
int *A=(int *) malloc( n*sizeof(int));
for(i=0;i<n;i++){
A[i]=i+1;}
for(i=0;i<n;i++){
printf(“%d”, A[i]);
int *A=(int *) calloc( n,sizeof(int))
}}
Motivation
 Suppose a variable number of elements, such as
employee records, we would be forced to declare an array
large enough to hold the maximum number of employees.
 If the size is underestimate, then forced to either recompile
the application with a larger size or to take other
approaches.
 If the size is overestimate, then we will waste space.
 The ability to dynamically allocate memory also helps
when dealing with data structures using a variable
number of elements, such as a linked list or a queue.
 This is done manually using functions to allocate and
deallocate memory. The process is referred to as dynamic
Contd.
Dynamic Memory Allocation
 Dynamic memory is allocated from the heap.
 Memory space required can be speci ed at the time of execution.
 C supports allocating and freeing memory dynamically using
library routines.
Memory Allocation Process in C
Contd.
 The program instructions and the global
variables are stored in a region known as
permanent storage area.
 The local variables are stored in another area
called stack.
 The memory space between these two areas is
available for dynamic allocation during
execution of the program.
– This free region is called the heap.
– The size of the heap keeps changing.
Contd.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a;
int *p;
p=(int*)malloc(sizeof(int));
*p=10;
free(p);
p=(int*)malloc(sizeof(int));
*p=20;
}
Memory Allocation Functions
These functions are found on most systems in the
stdlib.h header le:
 malloc
– Allocates requested number of bytes and returns a pointer to the
rst byte of the allocated space.
 calloc
– Allocates space for an array of elements, initializes them to zero
and then returns a pointer to the memory.
 free
– Frees previously allocated space.
 realloc
– Modi es the size of previously allocated space
Contd.
int *pi = (int*) malloc(sizeof(int));
*pi = 5;
printf("*pi: %d\n", *pi);
free(pi);
 malloc function single argument speci es the number of
bytes to allocate
 If successful, it returns a pointer to memory allocated
from the heap.
 If it fails, it returns a null pointer.
Contd.
Function Description
malloc Allocates memory from the heap
realloc Reallocates memory to a larger or
smaller amount based on a previously
allocated block of memory
calloc Allocates and zeros out memory from
the heap
free Returns a block of memory to the
heap
Contd.
 A block of memory can be allocated using the
function malloc.
– Reserves a block of memory of speci ed size and
returns a pointer of type void.
– The return pointer can be type-casted to any
pointer type.
General format:
ptr = (type *) malloc (byte_size);
Examples
 p = (int *) malloc(100 * sizeof(int));
Contd..
char *pc = (char*) malloc(6);
for(int i=0; i<8; i++) {
*pc[i] = 0;
}
 Extra memory has been allocated at the end
of the six-byte string.
calloc()
 The calloc function will allocate and clear memory at
the same time.
Its prototype follows:
void *calloc(size_t numElements, size_t elementSize);
 malloc() doesn’t initialize the allocated memory.
 calloc() allocates the memory and also initializes the
allocates memory to zero.
realloc()
 Periodically, it may be necessary to increase or decrease the
amount of memory allocated to a pointer.
int main()
{
int n;
printf(“Ente sizeof array”);
scanf(“%d”, &n);
int *A=(int *) malloc( n*sizeof(int));
for(i=0;i<n;i++){
A[i]=i+1;}
int *B=(int *)realloc(A, 2*n*sizeof(int)); // increase size of array
for(i=0;i<n;i++){ // reduce size of array will be n/2
Memory Leaks
 A memory leak occurs when allocated memory is never
used again but is not freed.
 This can happen when:
– The memory’s address is lost or memory is
unreferenced
– The free function is never invoked though it should be
– A problem with memory leaks is that the memory
cannot be reclaimed and used later.
 Memory leak is also called growth of garbage in heap
 The amount of memory available to the heap manager is
decreased.
Dangling Pointers
 If a pointer still references the original memory after it has
been freed, it is called a dangling pointer.
 The pointer does not point to a valid object.
 This is sometimes referred to as a premature free.
Result in a number of di erent types of problems
 Unpredictable behavior if the memory is accessed
 Segmentation faults when the memory is no longer
accessible
 Potential security risks
How was 1-D array dynamically
allocated?
 Sample code segment:
int *p, n, i;
scanf (”%d”, &n);
p = (int *) malloc (n * sizeof(int));
 Array elements can be accessed equivalently as:
– p[i] = 20;
– *(p+i) = 20;
Methods to allocate space for 2-D
array
 Variable number of rows, xed number of
columns
 Variable number of columns, but xed number
of rows
 Both number of rows and columns variable
Allocating space for 2-D array n×5
 We can use a pointer of type (*q)[5] to
allocate space for the array of n rows and 5
columns.
int (*q)[5];
q = (int (*)[5]) malloc (n*5*sizeof(int));
2-D array
int main()
{ int (*q)[5],rows,i,j;
printf("Enter the number of Rows: ") ;
scanf("%d", &rows);
q = (int (*)[5]) malloc (rows*5*sizeof(int));
for(i=0; i<rows; ++i)
for(j=0; j<5; ++j)
q[i][j]=2*i+3*j ; Enter the number of Rows: 3
for(i=0; i<rows; ++i) { 0 3 6 9 12
for(j=0; j<5; ++j) 2 5 8 11 14
printf("%d ", q[i][j]); printf("\n"); 4 7 10 13 16
}return 0;}
Allocating space for 2-D array 3×m
 Use a pointer array of size 3, where the ith
element of the array will point to the ith column
of length m.
– Possible to have di erent number of elements in
di erent rows.
 int *r[3], i;
 for (i=0;i<3;i++)
 r[i] = (int *) malloc (m*sizeof(int));
Contd.
int main() for(i=0; i<3; ++i) {
{ col = 2 * (i+1);
int *r[3], i, j, col; for(j=0; j<col; ++j)
for(i=0; i<3; ++i) { printf("%d ", r[i][j]);
col = 2 * (i+1); printf("\n");
r[i] = (int *) malloc (col*sizeof(int)); }return 0;}
for(j=0; j<col; ++j)
r[i][j] = i + j;
}
Dynamic allocation of r×c array
 We can allocate a 2-D array of variable number
of rows and columns, where both the number of
rows and the number of columns as inputs.
 int **s;
 s = (int **) malloc (r*sizeof(int *));
 for (i=0;i<r;i++)
 s[i] = (int *) malloc (c*sizeof(int));
Contd.
int main() for(i=0; i<row; ++i) {
{ for(j=0; j<column; ++j)
int **s, row, column, i, j; printf("%d ", s[i][j]);
printf("Enter Row & Column:\n") ; printf("\n") ;
scanf("%d%d", &row, &column) ; }
s = (int **) malloc(row*sizeof(int *)) ; return 0;
for(i=0; i<row; ++i) { }
s[i] = (int *) malloc(column*sizeof(int))
;
for(j=0; j<column; ++j)
s[i][j] = i+j ;
}
Questions ….
int main ()
{ int i, j;
int a [8] = {1, 2, 3, 4, 5, 6, 7, 8};
for(i = 0; i < 3; i++) {
a[i] = a[i] + 1;
i++;
}
i--;
for (j = 7; j > 4; j--) {
int i = j/2;
a[i] = a[i] - 1;
}
printf ("%d, %d", i, a[i]);
}
Test on pointers
Question-1 Question-2
char c[] = "GATE2017"; #include<stdio.h>
char *p =c; void f(int *p, int *q) {
p=q; *p=2;
printf("%s", p + p[3] - p[1]) ; }
int i=0, j=1;
int main()
{
f(&i, &j);
printf("%d %d\n", i,j); }
Solution:
02
Contd…
main() What is the output
void f(int* p, int m)
{ { m = m + 5;
Int a[ ]={10,20,30,40,50}; *p = *p + m;
Int *ptr; return; }
void main()
ptr=a; {
printf(“%u”, *++ptr+3); int i=5, j=10;
f(&i, j);
printf(“%u”, *(ptr--+2)+5); printf("%d", i+j);
printf(“%u”, *(ptr+3)-10); }
} o/p=30
Contd…
int main(){ void f(int , int );
int main(){
char s[]="IIITNRCSE"; int i=5;
int x=1,y; f(--i,i++);
y=x++ + ++x; f(++i, i--);
printf("%c", s[++y]); printf("%d", i++);}
return 0;} void f(int x, int y)
{
printf("%d%d", x++, y--);
}
Contd…
void printxy(int x, int y) {
int *ptr;
x=0;
ptr=&x;
y=*ptr;
*ptr=1;
printf(“%d, %d”, x, y);
}
The output of invoking printxy(1,1) is
Contd..
main() Output:
{ The value printed is 5
Int i; more than the integer
int *pi=&i; value entered.
scanf(“%d”,i);
printf(“%d”,i+5);
}
Contd.
int f(int x, int *py, int **ppz)void main() Output:
{ {
int y, z; int c, *b, **a;
**ppz += 1; c = 4;
z = **ppz; b = &c;
*py += 2; a = &b;
y = *py; x += 3; printf( "%d", f(c,b,a));
return x + y + z; }
}
Contd…
main()
{
int k=5;
int *p=&k;
int **m=&p;
ptintf(“%d%d%d”,k, *p,**m)
}
555
Contd…
int f (int * p, int n)
{
if (n <= 1) return 0;
else return max (f (p+1, n-1), p[0] - p[1]);
}
int main ()
{
int a[] = {3, 5, 2, 6, 4};
print f(" %d", f(a, 5));
}
The value printed by this program is ________.
Contd.
main() Output:
{ 1204
char s1[7]=“1234”,*p;
p=s1+2;
*p=‘0’;
printf(“%s”,s1);
}
Consider the following program written in pseudo-code.
Assume that x and y are integers
count (x, y)
{ The number of times that
if (y !=1 )
{ the print statement is
{
if (x !=1) executed by the call
print("*"); Count(1024,1024) is
Count (x/2, y);
}
else {
y=y-1; 1023 x 10 = 10230
Count (1024, y);
}
}
}
Contd.
void fun(int *p) #include <stdio.h>
{ int main()
int q = 10; {
p = &q;
} oat arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
int main() oat *ptr1 = &arr[0];
{ oat *ptr2 = ptr1 + 3;
int r = 20; printf("%f ", *ptr2);
int *p = &r;
fun(p); printf("%d", ptr2 - ptr1);
printf("%d", *p);
return 0;
}
Output:
}
Output: 90.500000
20 3
Pointer declarations
int *f()
f is function pointer to integer
int (*pf)()
pf is pointer to function which returns int
char **x
x is pointer to pointer to char
int (*x)[10]
x is pointer to array of [10] int
Contd.
int (*daytab)[13]
daytab is pointer to array of 13 integers.
void (*f[10]) (int, int)
f is an array of 10 of pointer to function(which
takes 2 arguments of type int) returning void
char (*(*x())[]) ()
x is a function returning pointer to array of pointers
to function returning char

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