TopBottom

Followers



Click on more
SUBSCRIBE

Enter your email address:

Delivered by FeedBurner



VIDEO

Announcement: wanna exchange links? contact me at ravikrak@yahoo.com
Showing posts with label C Language. Show all posts
Showing posts with label C Language. Show all posts

Introduction To Storage Classes

Posted by Ravi Kumar at Sunday, December 25, 2011
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

strong class provides information about their location and
visibility.The storage class decides the portion of the
program within which the variables are recognized.
A variables storage class tells us

1.where the variables would be stored.
2.What will be the initial value of the variable,if the
initial value is not specifically assigned.
3.What is the scope of the variable i.e., which functions
the value of the variable would be available.
4.What is the lifetime of the variable, i.e., how long the
variable exist.
There are 4 types of storage classes in C.
1.Automatic
2.Static
3.External
4.Register

Share |

Labels:

Problems In Structures

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

typedef struct
{
int data;
NODEPTR link;
}*NODEPTR;
A typedef defines a new name for a type and in similar
cases like the one shown below you can define a new
structure type and a typedef for it at the same time.
typedef struct
{
char name[20];
int age;
}emp;
typedef struct
{
int data;
NODEPTR link;
}*NODEPTR;
There is no error in this because a typedef declaration
cannot be used until it is defined.In the given code
fragment the typedef declaration is not yet defined at the
point where the link file is declared.To eliminate this
problem ,first give the structure a name("struct node").Then
declare the link field as a simple struct node as shown
below:

typedef struct node

{
int data;
struct node *link;
}*NODEPTR;
Another way to eliminate this problem is to disentangle
the typedef declaration from the structure definition as
struct node
{
int data;
struct node *link;
};
typedef struct node *NODEPTR;
Another way is to precede the struct declaration with the
typedef ,in which case we would use the NODEPTR typedef
when declaring the link field as
typedef struct node *NODEPTR
struct node
{
int data;
NODEPTR next;
};

In this case ,we declare a new typedef name involving
struct node even though struct node has not been completely
defined yet,this allowed to do.

2.void modify(struct emp *);
struct emp
{
char name[20];
int age;
};
main()
{
struct emp e={"sanjay",4};
modify( &e);
printf("\n %s%d",e.name,e.age);
}
void modify(struct emp *p)
{
strupr(struct emp *p)
p->age=p->age+2;
}

Share |

Labels:

Pointers And Structures In C Language

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

We know that the name of an array stands for the address of its zeroth element.The samething is true of the names of arrays of structure variables.Suppose product is an array variable of structtype.The name product represents the address of its zeroth element consider the following declaration.

struct inventory
{
char name[30];
int number;
float price;
} product[2],*ptr;
This statement declares product s an array of two elements,each of the type struct inventory and ptr as a pointer to data objects of the type struct inventory.
The assignment
ptr=product;
would assign the address of the zeroth element of
product to ptr.This is,the pointer ptr will now point to
product[0].Its members can be accessed using the following
notation.
ptr --> name
ptr--> number
ptr --> price
The symbol -->is called the arrow operator and is made
up of a minus sign and a greater than sign.Note that ptr-->
is simply another way f wrting product[0].When the pointer
ptr is incremented by one,it is made to point to the next
record. i.e,product[1].We could use the notation
(*ptr).number
to access the member number.The parantheses around *ptr
are necessary because the member operator "." has a
higher precedence than the operator *

A program to illustrate the use of a structure pointer
to manipulate the elements of an array of structures the
program highlights all the features discussed above.Note
that the pointer ptr(of type struct invert) is also used
as the loop control index in for loops

Share |

Labels:

Additional Features Of Structures

Posted by Ravi Kumar at Monday, September 26, 2011
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

The values of structure variables can be assigned to another
structure variable of the same type using the assignment
operators. It is not necessary to copy the structure elements
piecemeal.

1.
main()
{
struct employee
{
char name[10];
int age;
float sal;
};
struct employee e1={"sanjay",30,1000.00};
struct employee e2,e3;
/* piecemeal copying*/
strcpy(e2.name,e1.name);
e2.age=e1.age;
e2.sal=e1.sal;
/*copying all elements at one time */
e3=e2;
printf("\n %s %d %f",e1.name,e1.age,e1.sal);
printf("\n%s %d %f",e2.name,e2.age,e2.sal);
printf("\n%s %d %f",e3.name,e3.age,e3.sal);
}

OUTPUT:
sanjay 30 1000.0000
sanjay 30 1000.0000
sanjay 30 1000.0000

For copying arrays we have to copy the contents of the
array element by element.This copying of all structure elements
at one time has been possible only because the structure
elements are stored in contiguous memory locations.

2.One structure can be nested within another structure.Using
this facility complex data types can be Created.

Main()
{
struct address
{
char phoneno[15];
char city[30];
int pin;
};
struct emp
{
char name[];
struct address a;
};
struct emp e={"sneha","531046","Texas",507};
printf("\n name=%s phone=%s",e.name,e.a.phoneno);
printf("\n city=%spin=%d" ,e.a.city,e.a.pin);
}

OUTPUT:
name=sneha phone=531046
city=Texas pin=507

Share |

Labels:

Arrays With In The Structures

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

C permits the use of arrays as structure members.we can
use single or multidimensional arrays of type int or float.
Ex: struct marks
{
int number;
float subject[3];
student[2];
}
here,the member subject contains 3 elements,subject[0],
subject[1] and subject[2].These elements can be accessed
using appropriate subscripts. For example ,the name
student[1].subject[2]; would refer to the marks obtained
in the third subject by the second student.

We can use arrays inside the structures. We can use single
or multidimensional arrays of type int or float.For example,
the following structure declaration is valid.
struct marks
{
int number;
float subject[3];
}student[3];

Here,the member subject contains 3 elements,subject[0],
subject[1] and subject[2].These elements can be accessed
using subscripts like student[1].subject[2];would refer to
the marks obtained in the third subject by the second
student.
/*Arrays Within The Structures*/
main()
{
struct marks
{
int sub[3];
int total;
};
static struct marks student[3]={45,67,81,0,75,53,
69,0,57,36,71,0};
static struct marks total;
int i,j;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
student[i].total += student[i].sub[j];
total.sub[j] +=student[i].sub[j];
}
total.total +=student[i].total;
}
printf("STUDENT TOTAL \n\n");
for(i=0;i<=2;i++)
printf("student[%d] %d\n",i+1,student[i].total);
printf("SUBJECT TOTAL \n\n");
for(j=0;j<=2;j++)
printf("subject-%d %d\n",j+1,total.sub[j]);
printf("\n Grand Total = %d\n",total.total);
}
OUTPUT:
STUDENT TOTAL
student[1] 193
student[1] 197
student[1] 164
SUBJECT TOTAL
subject-1 177
subject-2 156
subject-3 221
Grand Total =554

Share |

Labels:

Structures and Functions

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

The main philosophy of C language is the use of functions.
C supports the passing of structure values as arguments to
function. In this ,the values of a structure can be
transferred from one function to another by using 3 methods.
The first method is to pass each member of the structure as
an actual argument of the function call. The actual arguments
are then treated independently like ordinary variables.This
method is inefficient when the structure size is large.
The second method involves passing of copy of entire
structure to the called function.Here ,the function is working
on a copy of the structure ,so any changes to structure member
within the function are not reflected in the original
structure (in the calling function).It is,therefore ,necessary
for the function to return the entire structure back to the
calling function. But all compilers may not support this
method of passing the entire structure as a parameter.
The third method employs a concept called pointers to pass
the structure as an argument. In this case,the address
location of the structure is passed to the called function.
This function can access the entire structure indirectly. This
is smiler to the way ,arrays are passed to functions. This
method is more efficient as compared to the second approach.
The general format of sending a copy of a structure to the
called function is:
function name(structure variable name)
The called function takes the following form:
data-type function name(st-name)
struct-type st-name
{
- - - - -
--------
return (expression);
}

1. The called function must be declared for its type,
appropriate to the data type it is expected to For example,
if it is returning a copy of the entire structure,then it
must be
declared as struct with an appropriate tag name.
2.The structure variable used as the actual argument and
the corresponding formal argument in the called function
must be of the same struct type.
3.The return statement is necessary only if the function
is returning some data .The expression may be any simple
variable or structure variable or an expression using
simple variables.
4.When a function returns a structure it must be assigned
to a structure of identical type in the calling function.
5.The called function must be declared in the calling
function for its type if it is placed after the calling
function.

Share |

Labels:

Inroduction To Structures

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

Arrays can be used to represent a group of data items
that belong to same type,such as int or float.However,
If we want to represent a collection of data items of
different types using a single name,then we cannot use
arrays.At this time,we use structures.Structure is used
to represent a set of attributes,such as student_name,
roll_number and marks.The individual structure elements
are referred to as members.

Consider a book database consisting of book name,
author,number of pages and price. We can define a
structure to hold this information as follows.

struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};

The keyword ‘struct’ declares a structure to hold the
details of four fields,namely title,author,pages and
price. These fields are nothing but members of structure
elements.Each member may belong to a different type of
data. book_bank is the name of the structure and is
called the structure tag.This will be used to declare
variables that have tag’s structure.
This declaration has not declared any variable. It
simply describes a format called template to represent
information as follows.......
struct book_bank
title array of 20 char’s
author array of 15 char’s
pages integer
price float

general declaration of a structure

struct tag_name
{
data_type member1;
data_type member2;
------------
------------
}
we can declare structure variables using the tag name
any where in the program.For example, struct book_bank,
book_bank1,book_bank2, book_bank3;
each one of these variables has 4 members as specified
by the template.The complete declaration is like ....
struct book_bank
{
char title[20];
int author[15];
int pages;
float price;
};
struct book_bank book1,book2,book3,book3;

These members do not occupy any memory until they are
associated with the structure variables such as book1.

In defining structure we may follow the syntax

1.The template is terminated with a semicolon.
2.While the entire declaration is considered as a
statement, each member is declared independently for
its name and type in a separate statement inside the
template.
3.The tag name such as book_bank can be used to declare
structure variables of its type,later in the program.

Normally structure definitions appear at the beginning
of the program profile,before any variables or functions
are defined. They also appear before the main,along with
macro definitions such as #define.
We can assign values to the member of a structure in a
no. of ways. The link between a member and a variable is
established using the member operator.Which is also known
as dot period or
period operator.

For example,
book1.price
is the variable representing the price of book1 and
can be treated like anyother ordinary variable.
Strcpy(book1.title,"BASIC");
book1.pages=250;
Like any other data type,a structure variable can be
initialized. A structure must be declared as static if
it is to be initialized inside a function.

main()
{
static struct;
{
int wt;
float ht;
}
student ={60,180.75};
}
we can initialize a structure by using different ways.
main()
{
struct st_record;
{
int wt;
float ht;
}
static struct st_record student1={60,170.75};
static struct st_record student2={63,170.65};
}

Another method is to initialize a structure variable
outside the function like...

struct st_record;
{
int wt;
float ht;
}
student1={60,170.75};
main()
{
static struct st_record student2={63,170.65};
}
C language does not permit the initialization of
individual structure members within the template. The
initialization must be done only in the declaration of
the actual variables.

Share |

Labels:

Questions On Pointers Through Structures

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

1.Can a structure contain a pointer to itself ?
Ans:Certainly such structures are known as self
referential structures

2.What would be the output of the following program ?
main( )
{
struct emp
{
char *n;
int age;
}

struct emp e1={"dravid",123};
struct emp e2=e1;
strupr(e2.n);
prntf("\n%s",e1n);
}
Ans: DRAVID
3.If the following structure is written to a file usng
fwrite( ) ,can fread( ) read it back successfully ?
Ans: No,Since the structure contains a char pointer
while writting the structure to
the disk using fwrite( )
only the value stored in the pointer would get written.
When this structure is read back the address would be
read back but it is quite unlikely that the desired
string would be present at this adress in memory.
4.What is the output of the following program:
main()
{
struct a
{
char ch[7];
char *str;
};
static struct a s1={"Nagpur","Bombay"};
printf("%c%c\n",s1.ch[0],*s1.str);
printf("%s%s\n",s1.ch,s1.str);
}
Output: N B
Nagpur Bombay
5.what is the output of the following program?
main()
{
struct s1
{
char *z;
int i;
struct s1 *p;
};
static struct s1 a[]={
{"Nagpur",1,a+1};
{"Raipur",2,a+2};
{Kanpur",3,a}
};
struct s1 *ptr=a;
printf("%s%s%s\n",a[0].z,ptr->z,a[2]p-z);
}
6.What is the output of the following program?
main( )
{
struct node
{
int data;
struct node *link;
};
struct node *p,*q;
p=malloc(sizeof(struct node));
q=malloc(sizeof(struct node));
printf("%d%d",sizeof(p),sizeof(q));
}
Output: 22

Share |

Labels:

Pointers And Structures

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

We know that the name of an array stands for the address of
its zeroth element.The samething is true of the names of
arrays of structure variables.Suppose product is an array
variable of structtype.The name product represents the
address of its zeroth element consider the following
declaration.

struct inventory
{
char name[30];
int number;
float price;
}
product[2],*ptr;
This statement declares product s an array of two elements,
each of the type struct inventory and ptr as a pointer to
data objects of the type struct inventory.

The assignment
ptr=product;
would assign the address of the zeroth element of product
to ptr.This is,the pointer ptr will now point to product[0].
Its members can be accessed using the following notation.

ptr --> name
ptr--> number
ptr --> price
The symbol -->is called the arrow operator and is made
up of a minus sign and a greater than sign.Note that ptr-->
is simply another way f wrting product[0].When the pointer
ptr is incremented by one,it is made to point to the next
record. i.e,product[1].
We could use the notation
(*ptr).number
to access the member number.The parantheses around *ptr
are necessary because the member operator "." has a higher
precedence than the operator *

A program to illustrate the use of a structure pointer
to manipulate the elements of an array of structures the
program highlights all the features discussed above.Note
that the pointer ptr(of type struct invert) is also used
as the loop control index in for loops

struct invent
{
char *name[20];
int number;
float price;
};
main( )
{
struct invent product[3],*ptr;
printf("INPUT\n\n");
for(ptr=product;ptr lessthan product+3;ptr++)
scannf("%s%d%f",ptr->name,ampercent ptr->number,
ampercent ptr->price);
printf("\n OUTPUT\n\n");
ptr=product;
while(ptr lessthan product+3)
{
printf("% -20s %5d %102f\n",ptr->name,
ptr->number,ptr->price);
ptr++;
}
}


Output:
INPUT
Washing-machine 5 7500
Electric-iron 12 350
Two-in-one 7 1250

OUTPUT:
Washing-machine 5 7500.00
Electric-iron 12 350
Two-in-one 7 1250.00

While using structure pointers, we should take care
of the precedence of operators.
The operators '->', '.',(),[] enjoy higher priority
among the operators.They bind very tightly with thier
operands
For example,given the definition
struct
{
int count;
float *p;
*ptr
}
then the statement ++ptr->count;
increments count,not ptr however,
(++ptr)->count; increments ptr first,and
then links count the statement
ptr++->count;increments ptr first,and then
links count the statement
ptr++->count; is legal and increments ptr
after accessing count.The following statements also behave
in the similar fashion.
*ptr->p Fetches whatever p points to
*ptr-p++ Increments p after accessing what
ever it points to
(*ptr->p)++ Increments whatever p points to
*ptr++->p Increments ptr after accessing
whatever it points to.
Passing of a structure as an argument to a function or a
function recieves a copy of an entire structure and returns
it after working on it.This method is inefficient in terms
of both.The execution speed and memory.
We can overcome this drawback by passing a pointer to
the structure and then using this pointer to work on the
structure members.Consider the following function:
Print_invent(item)
struct invent *item;
{ printf("Name:%s\n",item->name);
printf("price:%f\n",item->price);
}
this function can be called by
print_invent(&product)
The ormal argument item recieves the address of the
structure product an therefore it must be declared as a
pointer of type struct invent,which represents the
structure of product.

Share |

Labels:

Two Dimensional Array Of Characters

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

Our example program asks you to type your name.When you
do so,it checks against a master
list to see if you
are worthy of entry to the palace.

Example:

#include "string.h"
#define FOUND 1
#define NOTFOUND 0
main()
{
char masterlist[6][10]={"srujana",
"sneha",
"swathi",
"lavanya",
"ramya",
"kalyani"
};
int i,flag,a;
char yourname[10];
printf("\n Enter your name:");
scanf("%s",yourname);
flag=NOTFOUND;
for(i=0;i<=5;i++)
{
a=strcmp(&masterlist[i][0],yourname);
if(a==0)
{
printf("welcome,u can enter the palace");
flag=FOUND;
break;
}
}
if(flag==NOTFOUND)
printf("sorry,u r a trespasser");
}

OUTPUT:
Enter your name:keerthi
sorry,u r a trespasser

Enter your name:srujana
welcome,u can enter the palace.

Names can be supplied from keyboard as:
for(i=0;i<=5;i++)
scanf("%s",&masterlist[i][0]);
while comapring the strings through strcmp() note that
the addresses of strings are being passed to strcmp().
srujana\0 sneha\0 swathi\0 lavanya\0 ramya\0 kalyani\0
1001 1011 1021 1031 1041 1051
Here 1001,1011,....are the base adresses of successive
names. For example, even though 10 bytes are reserved for
storing the name "ramya", it occupies only 5 bytes. Thus 5
bytes go waste.

ARRAY OF POINTERS TO STRINGS :

pointer variable always contains an address. Therefore,
if we construct an array of pointers it would contain a
number of addresses. Array of pointers can be stored as
char *names[]={
"srujana",
"sneha",
"swathi",
"lavanya",
"ramya",
"kalyani"
};
One reason to store strings in an array of pointers is
to make more efficient use of available memory.

LIMITATIONS OF ARRAY OF POINTERS TO STRINGS:
When we are using a 2-D array of characters we are at
liberty to either initialize the strings where we are declaring
the array or receive the strings using scanf() function.

Example: main()
{
char *names[6];
int i;
for(i=0;i<=5;i++)
{
printf("\n enter name");
scanf("%s",names[i]); /*doesnot work*/
}
}
The program doesn't work because when we are declaring
the array it is containing garbage values. And it would be
definitely wrong to send these garbage values to scanf() as
the addresses where it should keep the strings received from
the keyboard.

Share |

Labels:

Pointers And Strings

Posted by Ravi Kumar at Sunday, September 25, 2011
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

We cannot assign a string to another,whereas we can assign
a char pointer to another char pointer. This is shown with an
example:

main()
{
char str1[]="hello";
char str2[10];
char *s="good morning";
char *q;
str2=str1;/*error*/
q=s;/*works*/
}
Also,once a string has been defined it cannot be initialized
to another set of characters.Unlike strings, such an operation
is perfectly valid with char pointers.

Example:

main()
{
char str1[]="hello";
char *="hello";
str1="bye";/*error*/
p="bye";/*works*/
}
THE const QUALIFIER:
The keyword const, if present, precedes the data type of a
variable. It specifies that the value of the variable will not
change throughout the program. Any attempt to vary the value
of variable will result into an error message from compiler.
const is usually used to replace # define d constants.

Example:

main()
{
float r,a;
const float,PI=3.14;
printf("\n Enter radius:");
scanf("%f",&r);
a=PI*r*r;
printf("Area=%f",a);
}

If a const is placed inside a function its effect would
be localised to that function,whereas if it is placed outside
all functions then its effect would be global.

RETURNING const VALUES:
A function can return a pointer to a constant string as
shown Example:

main()
{
const char *fun();
const char *p;
p=fun();
p='A';/error*/
printf("\n%s",p);
}
const char * fun()
{
return "Rain()";
}
Since the function fun() is returning a constant string we
cannot use the pointer p to modify it. The following
operations too would be invalid:

(a)main() cannot assign the return value to a pointer to a
non-const string.
(b)main() cannot pass the return value to a function that is
expecting a pointer to a non-const string.

Share |

Labels:

Objective Type Questions on Pointers

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

1.What would be the output of the following program?
#include "stdio.h"
main( )
{
printf( "%d %d", sizeof(NULL),sizeof(" " ) );
}

(a) 1 1
(b) 1 2
(c) 2 1
(d) 2 2

Ans: c

2.How many bytes are occupied by near,far and huge
pointers?

(a) 2,2,4
(b) 2,4,4
(c) 2,4,2
(d) 2,2,2

Ans: b

4.Can anything else generate a Null Pointer Assignment
error?

(a) Yes
(b) No
(c) Can't say
(d) None

Ans: a

5. Are the three declarations char **apple, char
*orange[ ], and char cherry [ ] [ ] same?

(a) Yes
(b) No
(c) Can't say
(d) None

Ans: b

6.Can two different near pointers contain two different
addresses but refer to the same location in memory?

(a) Yes
(b) No
(c) Can't say
(d) None

Ans: b

7. Can two different far pointers contain two different
addresses but refer to the same location in memory?

(a) Yes
(b) No
(c) Can't say
(d) None

Ans: a

8. Can two different huge pointers contain two different
addresses but refer to the same location in memory?

(a) Yes
(b) No
(c) Can't say
(d) None

Ans: b

9.Would the following program give any warning on compilation?

#include "stdio.h"
main( )
{
int *p1,i=25;
void *p2;
p1=&i;
p2=&i;
p1=p2;
p2=p1;
}

(a) Yes
(b) No
(c) Can't say
(d) None

Ans: b

10.Would the following program give any warning on compilation?

#include "stdioh"
main( )
{
float *p1,i=25.50;
char *p2;
p1=&i;
p2=&i;
}

(a) Yes. Suspicious pointer conversion in function main
(b) No
(c) Can't say
(d) None

Ans: a

11.What warning would be generated on compiling the following
program?

main( )
{
char far *scr;
scr=0*B8000000;
*scr = 'A';
}

(a) Suspicious pointer conversion in function main
(b) Non-portable pointer assignment in function main
(c) Can't say
(d) None

Ans: b

12.How would you eliminate the warning generated on compiling
the following program?

main( )
{
char far *scr;
scr=0*B8000000;
*scr = 'A';
}

(a) Use the typecast scr= (char *far ) 0*B8000000;
(b) Use the typecast scr= (char far * ) 0*B8000000;
(c) Use the typecast scr= (char **far ) 0*B8000000;
(d) Use the typecast scr= (char far ** ) 0*B8000000;

Ans: b

13. In a large data model (compact, large, huge) all pointers
to data are 32 bits long,whereas in a small data model (tiny,
small,medium) all pointers are 16 bits long

(a) True
(b) False
(c) Can't say
(d) None

Ans: a

14. A near pointer uses the contents of CS register
(if the pointer is pointing to code) or contents of DS
register (if the pointer is pointing to data) for the
segment part,whereas the offset part is stored in the
16-bit near pointer

(a) True
(b) False
(c) Can't say
(d) None

Ans: a

15. What would be the output of the following program?

main( )
{
char far *a=0*00000120;
char far *b=0*00100020;
char far *c=0*00120000;
if(a==b)
printf("\nHello");
if(a==c)
printf("\nHi");
if(b==c)
printf("\nHello Hi");
if(a>b && a>c &&b>c)
printf("\nBye");
}

(a) Hello
(b) Hi
(c) Hello Hi
(d) Bye

Ans: d

16. What would be the output of the following program?

main( )
{
char huge *a=0*00000120;
char huge *b=0*00100020;
char huge *c=0*00120000;
if(a==b)
printf("\nHello");
if(a==c)
printf("\nHi");
if(b==c)
printf("\nHello Hi");
if(a>b && a>c &&b>c)
printf("\nBye");
}

(a) Hello
(b) Hi
(c) Hello Hi
(d) all

ans: d

17. Are the expressions *ptr++ and ++*ptr same?

(a) Yes
(b) No
(c) Can't Say
(d) None
Ans: b

18.Can you write another expression which does the same
job as ++*ptr?

(a) (ptr*)++
(b) *ptr++
(c) ptr*++
(d) (*ptr)++

Ans: d

19. What would be the equivalent pointer expression for
referring the same element as a[i][j][k][l]?

(a) *(*(*(*(a+i)+j)+k)+l)
(b) *(*(*(*a[i])[j])[k])[l])
(c) both
(d) None

Ans: a

20. What would be the output of the following program ?
main( )
{
int arr[ ]={12,13,14,15,16};
printf("\n%d %d %d",sizeof(arr),sizeof(*arr),
sizeof(arr[0]));
}

(a) 10 4 4
(b) 10 4 2
(c) 10 2 2
(d) 10 2 4

Ans: c

21.What would be the output of the following program
assuming that the array begins at location 1002?

main( )
{
int a[3][4]={1,2,3,4,
5,6,7,8,
9,10,11,12
};
printf( "\n%u %u %u",a[0]+1,*(a[0]+1),*(*(a+0)+1));
}

(a) 1004 2 2
(b) 1004 4 4
(c) 1002 2 2
(d) 1002 4 4

Ans: a

22. What would be the output of the following program
assuming that the array begins at location 1002?

main( )
{
int a[2][3][4]={ {
1,2,3,4,
5,6,7,8,
9,1,1,2
},
{
2,1,4,7,
6,7,8,9,
0,0,0,0
}
};
printf("\n%u %u %u %d",a,*a,**a,***a);
}

(a) 1002 1002 1002 2
(b) 1002 1002 1002 1
(c) 1004 1004 1004 1
(d) 1004 1004 1004 2

Ans: b

23. In the following program how would you print 50
using p?

main( )
{
int a[ ]={10,20,30,40,50};
char *p;
p = (char *) a;
}

(a) printf("\n%d",*( (int *)p+4) );
(b) printf("\n%d",( (int *)p+4) );
(c) printf("\n%d",*( (int )p+4) );
(d) printf("\n%d",*( (int **)p+4) );

Ans: a

24.In the following program add a statement in the
function fun( ) such that address
of a gets stored
in j

main( )
{
int *j;
void fun(int **);
fun(&j);
}
void fun(int **k)
{
int a=10;
}

(a) *k=&a;
(b) &a=*k;
(c) &k=*a;
(d) *a=&k;

Ans: a

25.How would you declare an array of three function
pointers where each function receives two ints and
returns a float?

(a) float (arr[3])(int,int);
(b) int (arr[3])(float,float);
(c) int (*arr[3])(float,float);
(d) float(*arr[3])(int,int);

Ans: d

Share |

Labels:

Basic Pointers

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

Pointer Definition: Pointer is a variable which contains
the address of another variable.Reasons for using pointer:
1.A pointer enables us to access a variable that is
defined outside the function.
2.Pointers are more efficient in handling the data tables.
3.Pointers reduce the length and complexity of a program.
4.They increase the execution speed
5.The use of pointer array to character strings results
in saving of data storage space in memory.

Representation of a variable:
Consider the following statement
int *p;
int quantity=179;
p=&quantity;
Here p is a pointer variable of type integer,which
holds the address of the variable quantity.

Declaring and initializing pointers:
In c,every variable must be declared for its type since
pointer variable contain address that belong to a seperate
data type, they must be declared as pointers before we use
them.The declaration of a pointer variable takes the
following form.
data type *pt-name;
This tells the compiler three things about the variable
pt-name
1.The asterick(*) tells that the variable pt-name is a
pointer variable.
2.pt-name needs a memory location.
3.pt-name points to a variable of type data type.

for example,
int *p;
declares the variable p as apointer variable that
points to an integer data type.Remember that the type int
refers to the data type of the variable being pointed to
by p and not the type of the value of the pointer.

Program to print the address of a variable along with
its value.

main()
{
char a;
int x;
float p,q;
a='A';
x=125;
p=10.25,q=18.76;
printf("%c is stored at addr %u \n",a,&a);
printf("%d is stored at addr %u \n",x,&x);
printf("%f is stored at addr %u \n",p,&p);
printf("%f is stored at addr %u \n",q,&q);
}
Output:
A is stored at addr 4436
125 is stored at addr 4434
10.250000 is stored at addr 4442
18.760000 is stored at addr 4438.

Accessing variables using pointers

main( )
{
int x,y;
int *ptr;
x=10;
ptr=&x;
y=*ptr;
printf("value of x is %d\n\n",x);
printf("%d is stored at addr %u\n",x,&x);
printf("%d is stored at addr %u\n",*&x,&x);
printf("%d is stored at addr %u\n",*ptr,ptr);
printf("%d is stored at addr %u\n",y,&*ptr);
printf("%d is stored at addr %u\n",ptr,&ptr);
printf("%d is stored at addr %u\n",y,&y);
*ptr=25;
printf("\n Now x=%d\n",x);
}

Ouput:
value of x is 10
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
4104 is stored at addr 4106
10 is stored at addr 408. Now x=25.

Share |

Labels:

Objective Type Questions on string functions

Posted by Ravi Kumar at Friday, September 23, 2011
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

1.What would be the output of the following program?
main()
{
printf(5+"fascimile");
}
A. error B. fascimile C. mile D. none of the above

Ans: C

2.What would be the output of the following program?
main()
{
char str1[] = "Hello";
char str2[] = "Hello";
if(str1 == str2)
printf("\n Equal");
else
printf("\nUnequal");
}

A. Equal B. Unequal C. Error D. None of the above

Ans: B

3.What would be the output of the following program?

main()
{
printf("%c","abcdefgh"[4]);
}

A. Error B. d C. e D. abcdefgh

Ans: C

4.How would you output \n on the following screen?

Ans: printf("\\n");

5.What would be the output of the following program?

main()
{
char str[7] = "strings";
printf("%s", str);
}
A. error B. strings C. cannot predict D. none of the above

Ans: C
Here str[] has been declared as a 7 character array and
into it a 8 character string has been stored . This would
result into overwriting of the byte beyond the seventh
byte reserved for the array with a '\0'.There is always a
possibility that something important gets overwritten
which would be unsafe .

6.What would be the output of the following program?

main()
{
char ch = 'A';
printf("%d%d", sizeof(ch), sizeof('A'));
}

A. 1 1 B. 1 2 C. 2 2 D. 2 1

Ans: B

7. What would be the output of the following program?

main()
{
printf("\n%d%d%d", sizeof('3'), sizeof("3"), sizeof(3));
}
A 1 1 1 B. 2 2 2 C. 1 2 2 D. 1 1 1

Ans:B

8. What would be the output of the following program?

main()
{
char *str[] = {"Frogs", "Do", "Not", "Die",
"They", "Croak"};
printf("%d %d", sizeof(str), sizeof(str[0]));
}

Ans: 12 2

9. What would be the output of the following program?

main()
{
static char s[] = "Rendezvous";
printf("%d", *(s+strlen(s)));
}

Ans: 0

Explanation: No Rendezvous, but a zero is printed out.
Mentioning the name of the string gives the base address
of the string. The function strlen(s) returns the length
of the string s[], which in this case is 12. In the
printf(), using the 'contents of' operator , we are
trying to print out the contents of 12th address from the
base address of the string. At this address there is a
'\0' ,which is automatically stored to mark the end of the
string. The ASCII value of '\0' is 0, which is what being
printed by the printf().

10. What would be the output of the following program?
main()
{
char ch[20];
int i;
for(i=0; i<=19; i++)
*(ch+i) = 67;
*(ch+i) = '\0';
printf("%s" , ch);
}

Ans: CCCCCCCCCCCCCCCCCCC

Explanation:Mentioning the name of the array always gives
its base address . Therefore (ch+i) would give the address
of the ith element from the base address , and *(ch+i)
would give the value at the address , i.e the value of the
ith element . Through the for loop we store 67, which is the
ASCII value of upper case 'C' , in all locations of the
string.Once the control reaches outside the for loop the
value of i would be 19 , and in the 19th location from the
base address we store a '\0' to mark the end of the string.
This is essential , as the compiler has no other way of
knowing where the string is terminated .In the printf() that
follows , %s is the format specification for printing a string,
and ch gives the base address of the string .Hence starting
from the first element ,the complete string is printed out.

11. What would be the output of the following program?
main()
{
char str[20];
int i;
for(1=0;1<=18; i++)
i[str] = 'C';
i[str] = '\0';
printf("%s",str);
}

Ans:CCCCCCCCCCCCCCCCCCC

Explanation: If your concept of arrays is fool-proof , you
should find the above o/p only natural. If not, here's your
chance to make it so. C makes no secret of the fact that it
uses pointers internally to access array elements .With the
knowledge of how array elements are accessed using pointers,
we can think of str[i] as *(str+i). Basic maths tells us
that *(str+i) would be same as *(i+str). And if str[i] is
same as *(str+i), then naturally *(i+str) would be same as
i[str].Thus, we can conclude that all the following
expressions are different ways of referring the ith element
of the string:
str[i]
*(str+i)
*(i+str)
i[str]
Hence, through the for loop upper case C is stored in all
the elements of the string. A '\0' is stored to mark the end
of the string, and then the string is printed out using
printf().

12.What would be the output of the following program?

main()
{
char str[20];
static int i;
for(; ;)
{
i++[str] = 'A' + 2;
if(i == 19)
break;
}
i[str] = '\0';
printf("%s",str);
}

Ans:CCCCCCCCCCCCCCCCCCC

13. What would be the output of the following program?

main()
{
static char str[]={48,48,48,48,48,48,48,48,48,48};
char *s;
int i;
s = str;
for( i = 0; i<=9; i++)
{
if(*s)
printf("%c", *s);
s++;
}
}

Ans: 0000000000

Explanation: In all 10 elements of str[], an integer , 48
is stored. Wondering whether a char string can hold ints?
The answer is yes, as 48 does not get stored literally in
the elements. 48 is interpreted as the ASCII value of the
character to be stored in the string. the character corr-
esponding to ASCII value 48 happens to be 0, which assig-
ned to all the locations of the string.'s', a character
pointer, is assigned the base address of the string str[].
Next , in the if condition,the value at address contained
in s is checked for truth/falsity.As 0 represents ASCII 48,
the condition evaluates to true every time, until the end
of the string is reached. At the end of the string a '\0',
i.e ASCII 0 is encountered , and the if condition fails.
Irrespective of whether the condition is satisfied or not,
's' is incremented so that each time it points to the
subsequent array element .This entire logic is repeated
in the for loop , printing out 10 zeros in the process.

14. What would be the output of the following program?

main()
{
static char str[]={0,0,0,0,0,0,0,0,0,0};
char *s;
int i;
s = str;
for( i = 0; i<=9; i++)
{
if(*s)
printf("%c", *s);
s++;
}
}

Ans: No output

Explanation: Though you may not have expected zeros to be
outputted this time,you surely did expect some output! We
stored the character corresponding to ASCII 0 in all 10
elements of the string. Next, we assigns s, a char pointer,
the base address of the string . Though the for loop , we are
attempting to print out all elements one by one , but not
before imposing the if condition.The if is made to test the
value at address contained in 's' before the execution of the
printf( ) .The first time , *s yields ASCII 0. Therefore the
if condition reduces to if(0) , and as 0 stands for falsity,
the condition fails. Hence ,'s'is incremented and control
loops back to for without executing the printf(). The same
thing happens the next time around , and the next, and so on,
till the for loop ends, resulting in no output at all.

15. What would be the output of the following program?

main()
{
static char s[]="C Smart!!";
int i;
for(i =0; s[i]; i++)
printf("%c%c%c%c\n",s[i],*(s+i),i[s],*(i+s));
}

Ans: C C C C
S S S S
m m m m
a a a a
r r r r
t t t t

! ! ! !
Explanation:The above program rubs in the point that s[i],
i[s],*(s+i) and *(i+s) are various ways of referring to the
same element, that is the ith element of the string s. Each
element of the string is printed out for four times,till the
end of the string is encountered. Note that in the for loop
there is an expression s[i] in the condition part. This means
the loop would continue to get executed till s[i] is not equal
to zero. We can afford to say this because a string always ends
with a '\0', whose ASCII value is 0. Thus the for loop will be
terminated when the expression s[i] yields a '\0'.

16. What would be the output of the following program?
main()
{
static char s[] = "Oinks Grunts and Guffaws";
printf("%c\n", *(&s[2]));
printf("%s\n", s+5);
printf("%s\n", s);
printf("%c\n", *(s+2));
printf(%s\n", s);
}

Ans: n
Grunts and Guffaws
Oinks Grunts and Guffaws
n
404
Explanation: In the first printf() the address of operator, &
gives the address of the second element of the string . Value
at this address is 'n' , which is printed out by the printf()
using %c. since s gives the base address of the array , (s+5)
would give the address of the fifth element from the base
address . This address is passed to the second printf() .
Using the format specification %s , the contents of the string
are printed out the 5th element onwards.The third printf()
prints the entire string , as the base address of the string
is being passed to it. The fourth printf() is made to print
the second character of the string , as *(s+2) is nothing but
s[2]. Thus 'n'gets printed.Does the o/p of the final printf()
surprise you by printing out a number , 404?

Note that the format specification %d is used with s, which
gives the base address of the string. It happened to be 404
when we executed the program, which got printed out. On
executing the same yourself, you may get any other address,
depending on what address is allotted to the string by the
compiler.

17.What would be the output of the following program?
main()
{
static char s[25] = "The cocaine man";
int i =0;
char ch;
ch = s[++i];
printf("%c%d\n",ch,i);
ch = s[i++];
printf("%c%d\n",ch,i);
ch = i++[s];
printf("%c%d\n",ch,i);
ch = ++i[s];
printf("%c%d\n",ch,i);
}
Ans: h 1
h 2
e 3
! 3

18.What would be the output of the following program?

main()
{
static char arr[] = "pickpocketing my piece of mind";
int i:
printf("%c\n", *arr);
arr++;
printf("%c\n", *arr);
}

Ans: Lvalue required in function main

Share |

Labels:

Limitations of array Pointers to strings

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

When we are using a two-dimensional array of characters
we are at liberty to either initialize the strings where we
are declaring the array, or receive the stringsusing
scanf() function. However,when we are using an array of
pointers to stringswe can initialize the strings at the
place where we are declaring the array,but we cannot receive
the strings from keyboard using scanf().Thus the following
program would never work out.

main()
{
char *names[6];
int i;
for(i =0; i<= 5; i++)
{
printf("\n enter name");
scanf("%s",names[i]);
}
}
The program doesn't work because; when ae are declaring
the array it is containing the garbage values. And it
would be definitely wrong to send these garbage values to
scanf() as the address where it should keep the strings
received from the keyboard.
Write a function xstrstr() that will return the position
where one string is present within another string. If the
second string doesn't occur in the first string xstrstr()
should return a 0.

For example, in the string "somewhere over the rainbow",
"over" is present at location 11.

main()
{
static char str1[] = "somewhere over the rainbow";
static char str2[] = "over";
printf("string found at %d", xstrstr(str1, str2));
}
xstrstr(s1, s2)
char *s1, *s2;
{
int i, a, len1, len2;
len1 = strlen(s1);
len2 = strlen(s2);
for(i = 0; i<=(len-1); i++)
{
a = strncmp((s1+i) , s2, len2);
if(a == 0)
return (i+1);
}
return (0);
}

output:
string found at 11

Explanation: The two strings have been declared as str1[]
and str2[] in main from where the base addresses are sent
to the function xstrstr() for searching the second string
in the first one. In xstrstr(), len1 and len2 store the
lengths of the 2 strings withbase addresses s1 and s2
respectively .In the for loop, i is incremented len1 number
of times. As many times, the standard library function
strncmp(t,s, n) gets called.This function compares the
first n elements of strings starting from t and s and
returns 0 if they are equal.The first time through the for
loop, i is 0. Hence strncmp() compares the first len2
(here len2 is equal to 4) elements of strings starting
from (s1+0) i.e s1and s2 a collects a non-zero value, as
the first four elements of the two strings are found to be
different.The control therefore reverts back to the for
where i is incremented to 1.So the second time through the
loop strncmp() compares first len2 elements
of strings
starting from s1 and s2. Literally first 4 elements of
"somewhere over the rainbow" and "over" are compared .Once
again a collects a non-zero value and i is incremented a
second time.this goes on similarly till i is 10, when s1+10
denotes the base address of the string "over the rainbow".
This time a is assigned a 0,as both the strings have o, v, e
and r as the first four elements, and control returns to
main() with i+1, i.e 11.This is the position of the second
string in the first one.Suppose the second string is not
present in the first string at all, then at no time a would
contain 0. Thus the return statement after the loop would
return 0,signifying that the second string was not found in
the first one.

Share |

Labels:

Array Of Pointers To Strings

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

As we know , a pointer variable always contains an
address. Therefore , if we construct an array of pointers
it would contain a number of addresses.Let us see how the
names in the earlier example can be stored in the array of
pointers.

char *names[] = { "akshay", "parag", "raman",
"srinivas", "gopal", "rajesh"};
In this declaration names[] is an array of pointers.It
contains base addresses of respective names.That is. base
address of "akshay" is stored in names[0], base address of
"parag" is stored in names[1] and so on. In the
two-dimensional array of characters,the strings occupied
60 bytes.As against this ,in array of pointers,the strings
occupy only 41 bytes.
Note that in two-dimensional array of characters ,the
last name ended at location number 1060,whereas in array
of pointers to strings , it ends at 1041.A substantial
saving, you would agree. But realise that actually 19
bytes are not saved, since 10 bytes are sacrificed for
storing the address in array names .Thus ,one reason to
store strings in an array of pointers is to make a more
efficient use of available memory.
Another reason to use an array of pointers to store
strings is to obtain greater ease in manipulation of the
strings. This is shown by the following programs.
The first one uses a two-dimensional array of characters
to store the names, whereas the second uses an array of
pointers to strings .
The purpose of both the programs is very simple.
We want to exchange the position of the names "raman"
and "srinivas".

Exchange names using 2-D array of characters

main()
{
char names[][10] = { "akshay", "parag", "raman",
"srinivas", "gopal", "rajesh"};
int i;
char t;
printf("\n original: %s%s",&names[2][0], &names[3][0]);
for(i = 0; i<= 9; i++)
{
t = names[2][i];
names[2][i] = names[3][i];
names[3][i] = t;
}
printf("\n New:%s%S", &names[2][0], &names[3][0]);
}
output:
Original: raman srinivas
New: srinivas raman

Note that in this program to exchange the names we are
required to exchange corresponding characters of the two
names. In effect , 10 exchanges are needed to interchange
two names Let us see if the number of exchanges can be
reduced by using an array of pointers to strings. Here is
the program...

main()
{
char *names[] = { "akshay", "parag", "raman",
"srinivas", "gopal", "rajesh"};
char *temp;
printf("original: %s %s", names[2], names[3]);
temp = names[2];
names[2] = names[3];
names[3] = temp;
printf("\n New: %s %s", names[2], names[3]);
}

output:
original: raman srinivas
New: srinivas raman

Share |

Labels:

Programs In String Handling Functions

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

1.Is the folowing program correct or not? yes/no

main()
{
char *str1 = "United";
char * str2 = "Front";
char *str3;
str3 = strcat(str1, str2);
printf("\n %s", str3);
}

Ans: No, since what is present in memory beyond "united" is
not known and we are attaching "Front" at the end of "United",
thereby overwriting something, which is unsafe thing to do.

2.How would you improve the code in the above program?

Ans: main()
{
char str1[15] = "United";
char *str2 = "Front";
char *str3;
str3 = strcat(str1,str2);
printf("\n%s", str3);
}

3. Write a program to enter the two strings and compare them
without using any standard function. Determine whether the
strings are identical or not.
Also display the number of position where the characters are
different.

main()
{
static char sr[10], tr[10];
int diff = 0,i;
clrscr();
printf("\n enter the string");
gets(sr);
printf("enter the second string");
gets(tr);
for(i =0; i<10;i++)
{
if(sr[i] ==tr[i]);
continue;
else
{
printf("%c %c\n", sr[i],tr[i]);
diff++;
}
}
if(strlen(sr) == strlen(tr)&&diff == 0)
puts("\n The two strings are identical");
else
printf("\n The two strings are different
at %d places", diff);
getch();
}

output:
enter the string: BEST LUCK
enter the second string: GOOD LUCK
G B
O E
O S
D T

4.Write a program to concatenate two strings without the use
of standard library functions

main()
{
char name[50], fname[15], sname[15], lname[15];
int i,j,k;
printf("first name");
grts(fname);
printf("second name");
grts(sname);
printf("last name");
grts(lname);
for(i =0; fname[i]!='\0'; i++)
name[i]=fname[i];
name[i]=' ';
for(j =0; sname[j]!='\0'; j++)
name[i+j+1]=sname[i];
name[i+j+1]=' ';
for(k =0; lname[k]!='\0'; k++)
name[i+j+k+2]=lname[k];
name[i+j+k+2]='\0 ';
printf("\n\n");
printf("complete name after concatenation\n");
printf("%s", name);
getch();
}

output:
first name: MOHAN
second name:KARAMCHAND
last name: GANDHI
complete name after concatenation
MOHAN KARAMCHAND GANDHI

5.Write a program to display reverse of a string without using
standard library functions.

main()
{
char text[15];
int i = 0;
printf("enter the string");
gets(text);
while(text[i[!='\0')
{
printf("\n 5c is stored at location %u", text[i],&text[i])
i++;
}
strrev(text);
printf("reverse string");
printf("%s",text);
i =0;
while(text[i]!='\0')
{
printf("\n %c is stored at location %u",text[i], &text[i]);
i++;
}
}

output:
enter string:ABC
A is stored at location 4054
B is stored at location 4055
C is stored at location 4056
reverse string:CBA
C is stored at location 4054
B is stored at location 4055
A is stored at location 4056

6.Write a program to find the number of words in a given
statement . Exclude spaces between them.

main()
{
char text[30];
int count = 0,i = 0;
printf("enter the line of text");
printf("give one space after each word");
gets(text);
while(text[i++]!='\0')
if(text[i]==32 || text[i]=='\0')
cout++;
printf("The number of words in line = %d\n", count);
}

output:
enter the line of text
give one space after each words
read books
The number of words in line = 2

Share |

Labels:

strcmp() function

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

This is a function which compares two strings to fin
out whether they are same or different.The two strings are
compared character by character until there is a mismatch
or end of one of the strings is reached, whichever occurs
first. If the two strings are identical , strcmp() returns
a value zero. If they aren't not, it returns the numeric
difference b/w the ASCII values of the first non-matching
pairs of characters. Here is a program which puts strcmp()
in action.

main()
{
char string1[] = "Jerry";
char string2[] = "Ferry";
int i, j, k;
i = strcmp ( string1, "Jerry");
j = strcmp ( string1, "string2");
k = strcmp ( string1, "Jerryboy");
printf("\n%d%d%d",i,j,k);
}

output:
0 4 -32

In the first call to strcmp(), the two strings are
identical-"Jerry" and "Jerry" and the value returned by
strcmp() is zero. In the second call ,the first character
of "Jerry" doesn't match with the first character of
"Ferry" and the result is 4, which is the numeric
difference b/w ASCII value of 'J' and ASCII value of 'F''.
In the third call to strcmp() also the same procedure
repeats.

Share |

Labels:

strcat() function

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

This function concatenates the source string at the
end of the target string. For example "Bombay" and "Nagpur"
on concatenation would result into a string "BombayNagpur".
Here is an example of strcat() at work.

main()
{
strcat(target, source);
printf("\n source string = %s", source);
printf("\n target string = %s", target);
}

output:source string = Folks
target string = HelloFolks

Note that the target string has been made big enough
to hold the final string .

Share |

Labels:

strcpy() function

Posted by Ravi Kumar at
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

This function copies the contents of one string into
another.The base address of the source and target strings
should be supplied to this function.Here is an example of
strcpy() in action.....

main()
{
char source[] = "sayonara";
char target[20];
strcpy(target, source);
printf("\n source string= %s", source);
printf("\n target string = %s", target);
}

output:
source string = sayonara
target string = sayonara
On supplying the base address , strcpy() goes on copying
the characters in source string into the target string till
it doesn't encounter the end of source string('\0'). It is
our responsibility to see to it that the target string's
dimension is big enough to hold the string being copied into
it. Thus , a string gets copied into another ,piece -meal ,
character by character . There is no short cut for this .

User-defined Function for strcpy():

main()
{
char source[] = "sayonara";
char target[20];
xstrcpy(target, source);
printf("\n source string= %s", source);
printf("\n target string = %s", target);
}
xstrcpy(char *t, char *s)
{
while (*s! = '\0')
{
*t = *s;
s++;
t++;
}
*t = '\0';
}

output:
source string = sayonara
target string = sayonara

Note that having copied the entire source string into the
target string ,it is necessary to place a '\0' into the
target string , to mark its end. If you look at the prototype
of strcpy() standard library function, it looks like this
strcpy(char *t, const char *s);
We didn't use the keyword constant in our version of
xstrcpy() and still our function worked correctly. So what is
the need of the const qualifier?what would happen if we add
the following lines beyond the last statement of xstrcpy()?
s = s-8;
*s = 'k';
This would change the source string to "Kayonara" . Can
we not ensure that the source string doesn't change even
accidentally in xstrcpy()? We can ,by changing the definition
as folows:
void xstrcpy (char *t,const char *s)
{
while(*s! ='\0')
{
*t = *s;
s++;
t++;
}
*t = '\0';
}

By declaring char *s as const we are declaring that the
source string should remain constant Thus the const qualifier
ensures that your program does not inadvertently alter a
variable that you intended to be a constant. It also reminds
anybody reading the program listing that the variable is not
intended to change

Share |

Labels: