C&ds 3rd Unit For Eee
C&ds 3rd Unit For Eee
C&ds 3rd Unit For Eee
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
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
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
1 2 3 4 5
1000 1002 1004 1006 1008
Address
Base class
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);
}
Pointer to pointers:
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
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>
#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)
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;
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;
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++;
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?
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.)
If you follow the rule of array initialization then you can write the above
statement as follows
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 () {
return 0;
When the above code is compiled and executed, it produces the following
result
1 strcpy(s1, s2);
2 strcat(s1, s2);
3 strlen(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);
6 strstr(s1, s2);
#include <stdio.h>
#include <string.h>
int main () {
char str3[12];
int len ;
strcpy(str3, str1);
len = strlen(str1);
return 0;
When the above code is compiled and executed, it produces the following
result
1. Strings as arrays:
where the beginning of the array is at some location in computer memory, for
example, location 1000.
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";
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]);
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 */
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:
Since we are talking about strings, which are made up of characters, we'll be
using pointers to characters, or rather, char *'s.
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];
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 |
--------
3. Passing 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)
{
OR
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.
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.
...
...
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).
5. string.h library:
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.
if (strcmp(str1, "apple") == 0)
printf("Equal\n");
else
printf("Not equal\n");
OR
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.
Want... Use...
a == b strcmp(a, b) == 0
... ...
o strcpy(dest, source)
strcpy(str1, "second");
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.
Also, strcpy() returns the destination string, but that return value is
often ignored.
o strcat(dest, source)
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.