Tutorial 8.1.a:
Check output of the following program.
void main ()
{
int a,*b,**c,***d,****e;
a=10;
b=&a;
c=&b;
d=&c;
e=&d;
printf(“\n a=%d b= %u c=%u d=%u e=%u”, a ,b, c, d, e);
printf(“\n a=%d a+*b= %d **c + ***d=%d ***d + ****e=%d ”,a,
a+*b, **c + ***d, ***d + ****e);
}
Tutorial 8.1.b:
Write a C program to swap two variables
void main()
{
int a=5,b=10;
printf(“Before Swap:\n a=%d and b=%d”,a,b);
swap(a,b);
printf(“After swap:\n a=%d and b=%d”,a,b);
swap_ptr(&a,&b);
printf(“After swap using pointer: \n a=%d and b=%d”,a,b);
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void swap_ptr(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output: Before Swap:
After Swap:
a=5 and b=10
a=10 and b=5
Tutorial 8.1.c:
Write a C program to read a string of length N and copy it to another
memory location using pointers and Dynamic memory allocation.
Soln:
#include<stdio.h>
#include<stdlib.h>
void strcopy(char *s,char *t)
{
while((*t++ = *s++) !='\0');
}
int main()
{
char *str1;
char *str2;
int len;
printf("Enter Length of the string: ");
scanf("%d",&len);
str1 = (char *)malloc(len*sizeof(char));
str2= (char *)malloc(len*sizeof(char));
printf("\nEnter the String: ");
scanf("%s",str1);
strcopy(str1,str2);
printf("\n Input String stored in str1=%s and copied to str2=%s",str1,str2);
return 0;
}
Output: Enter Length of the string: 8
Enter the String: Pointers Input String stored in str1=Pointers and copied to str2=Pointers
Assignment 8.1:
Write a C program to read a string of
length N (given as input) the string memory should be dynamically allocated and then
write user defined functions performs the
following string operations. You are not allowed to use any string library
functions. Moreover array constructs like a[i] cannot be used.
a) strComp (char *S, char *T): compares two strings S and T .
return <0 if S<T
return 0 if S==T
return >0 if S>T, Here " < " or " > " implies less or greater according to
ASCII values.
Input Output
S= abc T= def -1
S= abc T= abc 0
S= def T= abc 1
b) strEnd (char *S, char *T):
returns 1 if T occurs at the end of string S
return 0 otherwise.
For Example: Input Output
S= pickpocketing T=pocket 0
Input Output
S= for your eyes T=yes 1
c) strRotate(char *str): Displays all possible rotations of a string;
For Example:
INPUT: abcdefg
OUTPUT:
gabcdef fgabcde
efgabcd defgabc cdefgab
bcdefga abcdefg
d) strReverse (char *S): Function accepts an array of
N strings of length K as input
argument and return the reverse of each of the strings.
I. Construct a 2-Dimensional array using dynamic memory
allocation to store the given input strings.
II. The input string are of different length.
III. Your strReverse( ) function must be “In Place”.
Hint: You can modify the Swap( ) function as shown. You have to use just two variables to swap.
in Tutorial 8.1.b.
For example:
Input : N
= 5 K=4,4,3,7,3
Enter strings :
Amit Ajay Mal aravind ram
Output : Reverse order of given strings :
tima yaja lam dnivara mar