C&ds 3rd Unit For Eee

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 26

1

C&DS-unit-III

Pointer Definition
Pointer is a variable which will hold the address of another variable,
It is a real power of c there are number of reasons for using pointers

Features of the pointer


Pointers save the memory space.
Execution time is faster because data is manipulated with
the address
The memory is accessed efficiently.
Pointers are used with data structures useful for representing
two dimensional and Multi dimensional arrays.
A pointer enables us to access a variable that is defined outside the function
Pointer is more efficient in handling the data tables
Pointers reduces the length of the program
They increase the speed of execution
We can use the memory dynamically
Quantity variable
Value
179
5000 address
Pointer represent with *(asterisk) symbol called value at address operator, the
value at address operator is also called indirection operator and address represent
with & symbol
Disadvantages of pointers

As the pointer directly deal with the address locations in the system memory,
improper handling of pointers can cause serious problems to the system.
If a pointer is arbitrarily assigned an address value which actually is storing the
addressof some other program, any change done to pointer value can affect the
working of other
program and my sometimes crash the application. Therefore at most care should
be takenwhile coding with pointer
Declaring and initializing the pointers

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


2

Pointer variables contains the address that belong to a separate data type, they must
be declared as pointers before we use them it would be declared as follows
Data type *pointer name

It tells the compiler three things


The asterisk tells that the variable pt_name is a pointer variable
Pt_name needs a memory allocation
Pt_name points to a variable of type data type
Ex: int * p
Int *x;
Float *f;
Char *y;
In the first statement x is an integer pointer and it tells to
the compiler that is holds the address of any integer variable the
indirection operator (*) is also called the deference operator.
Normal variable provides direct access to the values of the
variable whose address it stores.

Meaning of some pointer type variable declaration

Declaration what it means


Int p p is an integer
Int *p p is a pointer to an integer
Char p p is a character
Char *p p is a pointer to a character
Long p p is a long integer
Long *p p is a pointer to a long integer

Address Arithmetic (Pointer Operations):

Here are some limited operations that can be performed on pointers


(addresses). In fact we are only allowed to use increment/decrement and
addition/subtraction of integer value. When the pointer is incremented (p++) the
address value is incremented by length of the data type that it points to. This length
is called the scale factor. The length of the data type is given in the number of bytes
it occupies in the memory. In general on a 16 bit word length computer, the

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


3

Following is list of length of various data types:


char 1 byte
int 2 bytes
float 4 bytes
double 8 bytes
Long int 4 bytes
Short int 1 byte, etc
The address value in pointer is also decremented by scale factor when decrement
operator is used (p--).
When an integer n is added/subtracted to/from a pointer then the address value is
incremented/decremented by n times the scale facto

Pointers and arrays:

When an array is declared the compiler allocates a base address


and sufficient amount of storages to contain the entire element
with contigenious memory locations.
The base address is the first element (index 0) of an array.
Ex: int x[5]={1,2,3,4,5};
Suppose the base address x is 1000 we might be assume for each
integer as follows

X[0] x[1] x[2] x[3] x[4]


lements

1 2 3 4 5
1000 1002 1004 1006 1008
Address

Base class

X=&x [10] =1000


If we develop p is an integer pointer we can make the pointer p to
point to the array x.
P=x;
This is equal to p=&x [10];
We will access every value of an x using p++ level
P=&x[0]=1000

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


4

P+1=&x [1]=1002
P+2=&x [2] =1004
P+3=&x [3 ]=1006
P+4=&x [4] =1008
For finding the specifies address of element [x] we will use the
following principle.
Address of x [3] =base address +[3*scale factor of int)
=1000+3*2=1006
Ex:#include<stdio.h>
<include<conio.h>
main ()
{
Int *p,sum,I;
Int x[5] ={5,9,6,3,7};
I=0;
P=x;
Printf(element value address\n\n);
While (i<5)
{
Printf(x[%d]%d%u\n,I,*p,p);
Sum=sum+*p;
I++;
P++;
}
Printf(\n s um=%d\n,sum);
Printf(\n &x[0]=%n\n,&x[0]);
Printf(\n p=%u\n,p);
}

Element value address


X [0] 5 166
X [1] 9 168
X [2] 6 170
X [3] 3 172
X [4] 7 174

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


5

Sum=55 &x [0] =166 p=76

Pointer to pointers:

Pointer is a variable which holds the address of another variable


the pointer variable also have an address. The pointer variable
containing address of another pointer variable is called as pointer
to pointer.

Write a c program to print the value of variable using


pointer to pointer
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a=2,*p,**q;
P=&a;
Q=&p;
Clrscr();
Printf(\na=%d address of a =%u, a,&a);
Printf(\n *p value of a=%d address pf a=%u, *p,p);
Printf(\n **q value of a=%d address of a %d, **q,*q);
getch();
} In the above program variable p is declared as a
pointer, q is declared as pointer to another pointer. They are
declared as *p,, **q respectively. The address of variable a is
assigned to pointer p the address of pointer p is assigned to q,
the variable q contains address of a pointer variable. Hence, q is a
pointer variable.
Pointer to avoid

Pointers can also be declared as void type. Void pointers


cannot be deferential without explicit type conversion. Being void
the compiler cannot determine the size of the object that the

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


6

pointer pointy to, void declarations is possible void variables


declaration is not allowed
The declaration of void p displays an errors message size of p is
unknown or zero after compilation.
#include<stdio.h>
#include<conio.h>
Int p;
Float p;
Char c;
Void *pt=&p;
Void main(void)
{
Clrscr();
*(int*)pt=12;
Printf(\n=%d,p);
Pt=&d;
*(float*) pt=5.4;
Printf(\n r=%f,d);
Pt=&c;;
*(char*)pt=s;
Printf(\n c=%c,c);
}
Function Pointers
Function pointers are pointers, which point to the address of a function.
Declaration :

<return type> (* function_pointer)


(type1 arg1, type2 arg2, . );

int add ( int a, int b ) { return (a + b) ; }


int sub ( int a, int b ) { return (a b) ; }
int (*fp ) (int, int ) ; /* function pointer */
int main( ) {
fp = add;
printf(Sum = %d\n, fp( 4, 5 ) ) ;
fp = sub;

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


7

printf(Difference = %d\n, fp( 6 , 2 ) ) ;


}
Output :
Sum = 9
Difference = 4

Dynamic Memory Allocation (DMA) of pointers

Static memory allocation means allocating memory by compiler. When using


address operator, the address of a variable is assigned to a pointer.
Ex : int a = 20 ; int *p = &a ;
Dynamic memory allocation means allocating memory using functions like
malloc() and calloc(). The values returned by these functions are assigned to
pointer variables only after execution of these functions. Memory is assigned at run
time calloc ( ) is used for allocating memory space during the program execution
for derived data types such as arrays, structures etc.,
Example :
struct book
{
int no ; char name[20] ; float price ;
};
struct book b1 ;
b1 *ptr ;
ptr = (book *) calloc ( 10, sizeof ( book ) );

C allows us to create memory dynamically during the execution of the program. It


providesa set of functions for dynamic memory allocation. They are:
1.malloc()
2.calloc()
3.realloc()
4.free()
malloc():Is used to create a single block of memory dynamically. The size of the
memory location is being sent as a argument. The function malloc () returns the
address of the first byte in the memory created.

data_type *p;
//pointer of type data_type
p=(data_type*) malloc (sizeof(data_type));
//memory is created and address is stored in the pointer

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


8

The address returned by malloc should be type casted into corresponding


pointer type. To specify the size of memory location we use size of operator so that
it works on different system with different word length (16bit or 32 bit or so the
initial value stored in the new memory created by malloc() is unpredictable.If the
system is failed to allocate requested size of memory to any pointer variable then it
returns NULL address.

Calloc()
calloc() is used to create a collection of memory locations dynamically. It
is primarily used to allocate memory for arrays. This function takes 2 arguments,
first being the number of memory locations needed and second one is the size of
each memory location. The value in memory created is initialized to zero or NULL
depending on the data type
syntax :
data_type *p;p=(data_type *) calloc ( n, sizeof (data_type) );

The above statement creates n memory locations can store data of type data type
and return the address of first memory location. Therefore subsequent memory
locations can be accessed by incrementing the pointer p.

Realloc()

Realloc() used to adjusts the size of the memory location which is already
created. In normal classes, this function increases/decreases the size of memory
without changing the address. While adjusting the size, if needs more memory and
is not available at the current address then it changes the address and returns the
new address (after allocation the memory). This function needs two arguments,
first being the pointer to memory previously created, second should be new size
required for the memory location

p=(data_type*)malloc(sizeof(data_type));
//memory is created here
p=(data_type*)realloc(p,sizeof(data_type)+2);
//memory is resized here and stored in same pointer
Note: All the three function discussed above are defined in alloc.h (or) stdlib.h and
it need to be included while coding

Ex:#include<stdio.h>
#include<conio.h>

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


9

#include<stdlib.h>
void main()
{
int *p,sum=0;int i,n;
clrscr();
printf("Enter the number of values:");
scanf("%d",&n);p=(int *)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter the value of %d element: ",i+1);
scanf("%d",p+i);sum+=*(p+i);
}
printf("\n\nThe sum of all given numbers is %d",sum);
getch();
}
Free ()
free () is used to release the previously allocated memory to the system. When the
memory allocated is no longer needed then they should be freed using the free
function
syntax: free(pointer)

General Problems with Using pointers

Write a c program to print the addition of two numbers using pointers


#include<stdio.h>
#include<conio.h>
main()
{
long int a,b,*x,*y;
clrscr();
printf("enter the a,b values\n");
scanf("%d%d",&a,&b);
x=&a;
y=&b;
printf("%d\n%d",a,b);
printf("\n");
printf("%d\n%d",*x,*y);
getch();
}

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


10

Write a c program to print the swapping of given numbers using pointers


#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
clrscr();
printf("enter the a,b elements\n");
scanf("%d%d",&a,&b);
swap(a,b);
getch();
}
swap(int a,int b)
{
int *x,*y,t;
x=&a;
y=&b;
t=*x;
*x=*y;
*y=t;
printf("%d\n%d",*x,*y);
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
void swap (int a, int b);
a = 10;
b = 20;
printf("Value of a before function call : %d\n",a);
printf("Value of a before function call : %d\n" ,b);
swap (a,b);
printf("Value of a after function call : %d\n",a);
printf("Value of a after function call : %d\n" ,b);
getch();
}
void swap (int x, int y)
{
int temp;

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


11

temp = x;
x = y;
y=temp;
printf("Value of a during function : %d\n",x);
printf("Value of b during function : %d\n",y);
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
void swap(int *x, int *y);
clrscr();
a = 10;
b = 20;
printf("Value of a before function call : %d\n ",a);
printf("Value of a before function call : %d\n " ,b);
swap(&a, &b);
printf("Value of a after function call : %d\n",a);
printf("Value of a after function call : %d\n" ,b);
getch();
}
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y=temp;
printf("Value of a during function : %d\n ",*x);
printf("Value of b during function : %d\n",*y);
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i, a[ ] = {10, 20, 30, 40, 50, 60};
void display (int *num);
clrscr();
i = 0;

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


12

while (i<=5)
{
display(&a[i]);
i++;
}
getch();
}
void display(int *num)
{
printf(" %d\n", *num);
}

#include<stdio.h>
#include<conio.h>
void main()
{
int num[ ] = {10, 20, 30, 40 ,50, 60}, i;
void display (int *num);
clrscr();
i = 0;
while (i<=5)
{
printf("ADDRESS = %u",&num[i]);
printf(" ELEMENT = %d\n",num[i]);
i++;
}
getch();
}

#include<stdio.h>
#include<conio.h>
void main()
{ static int a[3][2] = {
{100, 200},
{300, 400},
{500, 600}
};
clrscr();
int *ptr1, i, j, n, m;

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


13

ptr1 = &a[0][0];
n=3;
m=2;
for(i=0; i<=n-1; i++)
{
printf("\n");
for(j=0;j<=m-1;j++)
{
printf("%d ",*ptr1);
ptr1++;
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
char a[] = "computers";
char *ptr;
clrscr();
ptr=&a[0];
while (*ptr !='\0')
{
printf("%c",*ptr);
ptr++;
}
getch()
}
#include<stdio.h>
#include<conio.h>
void main()
{
char a[] = "computers";
char *ptr;
int i=0;
clrscr();
ptr=&a[0];
while (*ptr !='\0')
{
i++;

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


14

ptr++;
}
printf( "Length of the given string is : %d\n",i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main ()
{
char *ptr1 [3];
clrscr ();
ptr1 [0] = "Hello ! ";
ptr1 [1] = "How are ";
ptr1 [2] = "you";
printf("%s %s %s",ptr1 [0] ,ptr1 [1] ,ptr1 [2]);
getch ();}

Strings

What is a String?

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


15

Note that along with C-style strings, which are arrays, there are also string
literals, such as "this". In reality, both of these string types are merely just
collections of characters sitting next to each other in memory. The only
difference is that you cannot modify string literals, whereas you can modify
arrays. Functions that take a C-style string will be just as happy to accept
string literals unless they modify the string (in which case your program will
crash). Some things that might look like strings are not strings; in
particular, a character enclosed in single quotes, like this, 'a', is not a string.
It's a single character, which can be assigned to a specific location in a
string, but which cannot be treated as a string. (Remember how arrays act
like pointers when passed into functions? Characters don't, so if you pass a
single character into a function, it won't work; the function is expecting a
char*, not a char.)

Strings are actually one-dimensional array of characters terminated by


a null character '\0'. Thus a null-terminated string contains the characters
that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the


word "Hello". To hold the null character at the end of the array, the size of
the character array containing the string is one more than the number of
characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above
statement as follows

char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C/C++

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


16

Actually, you do not place the null character at the end of a string constant.
The C compiler automatically places the '\0' at the end of the string when it
initializes the array. Let us try to print the above mentioned string

#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

printf("Greeting message: %s\n", greeting );

return 0;

When the above code is compiled and executed, it produces the following
result

Greeting message: Hello

C supports a wide range of functions that manipulate null-terminated


strings

S.N. Function & Purpose

1 strcpy(s1, s2);

Copies string s2 into string s1.

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


17

2 strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3 strlen(s1);

Returns the length of string s1.

4 strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.

5 strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

The following example uses some of the above-mentioned functions

#include <stdio.h>

#include <string.h>

int main () {

char str1[12] = "Hello";

char str2[12] = "World";

char str3[12];

int len ;

/* copy str1 into str3 */

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


18

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */

len = strlen(str1);

printf("strlen(str1) : %d\n", len );

return 0;

When the above code is compiled and executed, it produces the following
result

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

1. Strings as arrays:

In C, the abstract idea of a string is implemented with just an array of


characters. For example, here is a string:
char label[] = "Single";

What this array looks like in memory is the following:


------------------------------
| S | i | n | g | l | e | \0 |
------------------------------

where the beginning of the array is at some location in computer memory, for
example, location 1000.

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


19

Note: Don't forget that one character is needed to store the nul character (\0),
which indicates the end of the string.

A character array can have more characters than the abstract string held in it, as
below:
char label[10] = "Single";

giving an array that looks like:


------------------------------------------
| S | i | n | g | l | e | \0 | | | |
------------------------------------------

(where 3 array elements are currently unused).

Since these strings are really just arrays, we can access each character in the
array using subscript notation, as in:
printf("Third char is: %c\n", label[2]);

which prints out the third character, n.

A disadvantage of creating strings using the character array syntax is that you
must say ahead of time how many characters the array may hold. For example,
in the following array definitions, we state the number of characters (either
implicitly or explicitly) to be allocated for the array.
char label[] = "Single"; /* 7 characters */

char label[10] = "Single";

Thus, you must specify the maximum number of characters you will ever need
to store in an array. This type of array allocation, where the size of the array is
determined at compile-time, is called static allocation.

2. Strings as pointers:

Another way of accessing a contiguous chunk of memory, instead of with an


array, is with a pointer.

Since we are talking about strings, which are made up of characters, we'll be
using pointers to characters, or rather, char *'s.

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


20

However, pointers only hold an address, they cannot hold all the characters in a
character array. This means that when we use a char * to keep track of a string,
the character array containing the string must already exist (having been either
statically- or dynamically-allocated).

Below is how you might use a character pointer to keep track of a string.
char label[] = "Single";
char label2[10] = "Married";
char *labelPtr;

labelPtr = label;

We would have something like the following in memory (e.g., supposing that
the array label started at memory address 2000, etc.):
label @2000
------------------------------
| S | i | n | g | l | e | \0 |
------------------------------

label2 @3000
------------------------------------------
| M | a | r | r | i | e | d | \0 | | |
------------------------------------------

labelPtr @4000
--------
| 2000 |
--------

Note: Since we assigned the pointer the address of an array of characters, the
pointer must be a character pointer--the types must match.

Also, to assign the address of an array to a pointer, we do not use the address-
of (&) operator since the name of an array (like label) behaves like the address
of that array in this context. That's also why you don't use an ampersand when
you pass a string variable to scanf(), e.g,
int id;
char name[30];

scanf("%d%s", &id, name);

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


21

Now, we can use labelPtr just like the array name label. So, we could access
the third character in the string with:
printf("Third char is: %c\n", labelPtr[2]);

It's important to remember that the only reason the pointer labelPtr allows us
to access the label array is because we made labelPtr point to it. Suppose, we
do the following:
labelPtr = label2;

Now, no longer does the pointer labelPtr refer to label, but now to label2 as
follows:
label2 @3000
------------------------------------------
| M | a | r | r | i | e | d | \0 | | |
------------------------------------------

labelPtr @4000
--------
| 3000 |
--------

So, now when we subscript using labelPtr, we are referring to characters


in label2. The following:
printf("Third char is: %c\n", labelPtr[2]);

prints out r, the third character in the label2 array.

3. Passing strings:

Just as we can pass other kinds of arrays to functions, we can do so with


strings.

Below is the definition of a function that prints a label and a call to that
function:
void PrintLabel(char the_label[])
{
printf("Label: %s\n", the_label);
}

...

int main(void)
{

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


22

char label[] = "Single";


...
PrintLabel(label);
...
}

Since label is a character array, and the function PrintLabel() expects a


character array, the above makes sense.

However, if we have a pointer to the character array label, as in:


char *labelPtr = label;

then we can also pass the pointer to the function, as in:


PrintLabel(labelPtr);

The results are the same. Why??

Answer: When we declare an array as the parameter to a function, we really


just get a pointer. Plus, arrays are always automatically passed by reference
(e.g., a pointer is passed).

So, PrintLabel() could have been written in two ways:


void PrintLabel(char the_label[])
{
printf("Label: %s\n", the_label);
}

OR

void PrintLabel(char *the_label)


{
printf("Label: %s\n", the_label);
}

There is no difference because in both cases the parameter is really a pointer.

Note: In C, there is a difference in the use of brackets ( []) when declaring a


global, static or local array variable versus using this array notation for the
parameter of a function.

With a parameter to a function, you always get a pointer even if you use array
notation. This is true for all types of arrays.

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


23

4. Dynamically-allocated string:

Since sometimes you do not know how big a string is until run-time, you may
have to resort to dynamic allocation.

The following is an example of dynamically-allocating space for a string at run-


time:
#include <stdlib.h> /* for malloc/free */

...

void SomeFunc(int length)


{
char *str;

/* Don't forget extra char for nul character. */

str = (char *)malloc(sizeof(char) * (length+1));

...

Basically, we've just asked malloc() (the allocation function) to give us back
enough space for a string of the desired size. Malloc() takes the number of
bytes needed as its parameter. Above, we need the size of one character times
the number of characters we want (don't forget the extra +1 for the nul
character).

We keep track of the dynamically-allocated array with a pointer and can use
that pointer as we used pointers to statically-allocated arrays above (i.e., how
we access individual characters, pass the string to a function, etc. are the same).

Now, how do we get a string value into this newly-allocated array?

5. string.h library:

Recall that strings are stored as arrays (allocated either statically or


dynamically). Furthermore, the only way to change the contents of an array in
C is to make changes to each element in the array.

In other words, we can't do the following:


label = "new value"; /* No! */
label = anotherLabel; /* Wrong! */

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


24

(where anotherLabel is a string variable).

Aside: We could do that if label was a character pointer (instead of an array);


however, what would be happening is the pointer would be taking on the
address of a different string, which is not the same as changing the contents of
an array.

It would be annoying to have to do something like:


char name[10];

name[0] = 'R';
name[1] = 'o';
name[2] = 'b';
name[3] = '\0';

or to write loops all the time to do common string operations... Plus, we'd
probably forget the nul character half the time.

The C library string.h has several common functions for dealing with strings.
The following four are the most useful ones that we'll discuss:
o strlen(str)

Returns the number of characters in the string, not including the nul
character.
o strcmp(str1, str2)

This function takes two strings and compares them. If the strings are
equal, it returns 0. If the first is greater than the 2nd, then it
returns some value greater than 0. If the first is less than the 2nd, then it
returns some value less than 0.

You might use this function as in:


#include <string.h>

char str1[] = "garden";

if (strcmp(str1, "apple") == 0)
printf("Equal\n");
else

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


25

printf("Not equal\n");

OR

if (strcmp(str1, "eden") > 0)


printf("'%s' comes after 'eden'\n", str1);

The ordering for strings is lexical order based on the ASCII value of
characters. Remember that the ASCII value of 'A' and 'a' (i.e.,
upper/lowercase) are not the same.

An easy way to remember how to use strcmp() to compare 2 strings


(let's say a and b) is to use the following mnemonics:

Want... Use...
a == b strcmp(a, b) == 0

a<b strcmp(a, b) < 0

a >= b strcmp(a, b) >= 0

... ...
o strcpy(dest, source)

Copies the contents of source into dest, as in:


#include <string.h>

char str1[10] = "initvalue";

strcpy(str1, "second");

Now, the string str1 contains the following:


-------------------------------------------
| s | e | c | o | n | d | \0 | u | e | \0 |
-------------------------------------------

and the word "initvalue" has been overwritten. Note that it is the first nul
character (\0) that determines the end of the string.

When using strcpy(), make sure the destination is big enough to hold
the new string.

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM


26

Aside: An easy way to remember that the destination comes first is


because the order is the same as for assignment, e.g:
dest = source

Also, strcpy() returns the destination string, but that return value is
often ignored.

o strcat(dest, source)

Copies the contents of source onto the end of dest, as in:


#include <string.h>

char str2[10] = "first";

strcat(str2, " one");

Now, the string str2 contains the following:


------------------------------------------
| f | i | r | s | t | | o | n | e | \0 |
------------------------------------------

When using strcat(), make sure the destination is big enough to hold
the extra characters.

Aside: Function strcat() also returns the destination string, but that
return value is often ignored.

Prepared by Y.Amaraiah Assit.profesor,BITS,KHAMMAM

You might also like