Dec 3, 2019

3 Pointers and Arrays






Pointers:  
A program  and its data is stores in the computer’s main memory which is like a row of cells and each is capable of holding a byte and each having an address.  The compiler keeps track of all variables used by the program and their addresses.

A pointer variable contains the address of a memory location.  It provides an indirect way of accessing a value stored in the memory.  Any address can be stored in a pointer variable.  It can be of an existing variable or an arbitrary address.  When a pointer variable contains the address of another variable, it is said to be pointing to that variable.  A pointer variable can point to any other variable of any type and even to a pointer.

Declaration of pointer variable: 
Pointers are declared using(*) operator 
e.g. type *ptrname; 

where type can be any user data type and ptrname is a pointer of that data type.  
For example
int *iptr;
char *cp;
float *ptrfloat;

once a pointer variable is declared it can be made to point to a variable with the help of address operator(&) as
int num;
int *iptr;
iptr = & num;

hence integer pointer iptr points to variable num.

Once the pointer is defined, the variable it points to can be accessed using the indirection operator(*) which is also called the dereferencing operator.
#include<stdio.h>
void main ( )
{
int num =50;
int *ip;
ip =&num;
printf(“num =%u\n”,num);
printf(“&num =%u\n”,&num);
printf(“ip =%u\n”,ip);
printf(“*ip =%u\n”,*ip);
}

Pointer as function arguments:
pointers are also used to pass arguments to a function by reference.  The function is passed pointer to the argument whose value is to be changed since the function has the address of the argument it can directly operate on its contents, thus permanently changing its value.

#include<stdio.h>
void swap(int a, intb)
void main( ){
int x,y;
x=0;
y=20;
swap(&x,&y);
printf(“x=%d y=%d”,x,y);
}
void swap(int *a,int *b)
{
int t;
t=*a;
a=b;
*b=t;
}

pointers and arrays:  
In C arrays and pointer are very closely related.  C compiler coverts all arrays to pointers before operating on them.  Also any operation which is to be performed on array can be performed by operating on the pointer to the first element of the array.

Array: 
An array is a set of related data items, have the same storage class and can be accessed by common name.  An array is a derived data type.  Array can be declared as
Type arrayname[n];

Where type is the data type of variables forming the array, n is the number of elements which will stored together.  The array can be referred to and operated upon by using the name arrayname.
Eg. int marks[10];

Here array marks is an array of ten integers.  Each element of an array is stored in adjacent memory location.  Array name is always refers to beginning of the array and the size in square brackets has to be constant.  An index is used in square brackets following the name of the array, to uniquely identify a particular element.  An index can be in the range of zero to one less than the size of array.  As an

array[0] refers to first element of the array.
Array[1]  refers to second element of the array.   And so on.

After declaration, and array variable can be used just like a normal variable of the array type.

Array Initialization: 
All elements in an array can not be initialized automatically.  Each element of an array has to be initialized separately either in the declaration statement, if the array size is small or by using a for loop.
e.g.  int marks[5] = {0,0,0,0,0};
int some[10] = {1,2,3,4,5,6,7,8,9,10};
int big_array[100],sub;
for(sub = 0; sub<<100; ++sub)
big_array [sub] = 0;

Example  /* Accepting 10 numbers and to print them in ascending order */
# include <stdio.h>
void swap(int *a , int *b);
void accept (int *array);
void sort(int array []);
void print(int *array);
void main( ){
int array [10];
accept(array);
 sort (array);
print(array);
}
void accept (int *array){
int x;
for (x=0;x<<10;++x)
{
printf(“Enter a number %d:”, x+1);
scanf(“%d”,array[x]);
}
}
void sort(int array[]){
int x,y;
for(x=0; x<<10; ++x)
{
for(y=x+1; y<<10; ++y)
{
if(array[x]>array[y])swap(&array[x],&array[y]);
}
}
void print(int *array){
printf(“\n Array in ascending order:\n”);
for(x=0;x<<10;++x)
{
printf(“%d:%d\n”,x+1,*(array+x));
}
void swap(int *a,int *b){
int t;
t =  *a;
*a = *b;
 *b  = *a
}

Character Arrays and character Strings: 
Char Array can be declared and initialized as 
char name[5] = {‘A’,’B’, ‘C’, ‘D’, ‘E’};
OR char name[10] =  “Apple”;

The compiler initializes each element of char array by each of the characters given in quotes.  A null character (ASCII code 0) is also appended, by the compiler to the array.  The null-terminated char array is called as a String which is to be manipulated using character arrays.  As in above example name is a char array of size ten but initialized to only five characters. This is the actual size of string.  Rest of the positions in the array have an undefined value.  The function operating on this string has no way of knowing the actual size of the string. The null character is used for this purpose.  The function to print a string can be written as:
void print string( )
{
char name[10] = “Apple”;
int I;
for (I = 0; name[I] !=’\0’; ++I)
{
printf(“%c”, name[I]);
}

String  Handling functions:  

char getch(char * str): 
gets( ) function reads a line of characters from keyboard and stores in the given char array str.  It returns address of first character of the string.  It also appends a null character at the end of string.

Int puts(char *str): 
puts( ) function prints the string on the screen and returns number of characters printed.

Char * strcpy(char *dest, char *source): 
Copies the string to the string dest and returns address of the destination.

Int strcmp(char *si, char *s2):  
Compares two strings and returns a value.
< 0 if first is less than second
> 0 if first is greater than second
= 0 if first is equal to second.

Char *str cat(char *s1, char *s2):  
Appends second string at the end of first string and returns first’s Address.

Char *strrev(Char *string): 
Reverses the given string a returns its address.

Char *strchr(char *string, char ch): 
Returns address of first occurances of character given in ch from string, if found, otherwise returns a Null.  All string handling functions are declared in the Header file <string.h>

Example.
#include<string.h>
#include<stdio.h>
void main( )
{
char s1[100], s2[100], s3 [100];
int cmaflag;
printf(“enter first String:”);
gets(s1);
printf(“enter second String:”);
gets(s2);
cmpflag =strcmp(s1, s2);
if (Cmpflag = strcmp ==0)
printf (“%s is equal to %s \n”,s1 ,s2);
elseif (cmpflag<0)
printf (“%s is less than %s \n”,s1 ,s2);
else
printf (“%s is greater than %s \n”,s1 ,s2);
strcpy(s3, s1);
printf (“%s is reverse in %s \n”,strrev (s1) ,(s2));
}

Multidimensional Array and pointer to pointer: 
Multidimensional arrays are arrays with more than one indices or dimensions.  It can be declared as:
data type array name [n1],[n2]---[nx];
e.g. char page [60] [30];
int matrix [3] [3];
float loopup [30] [30];

page is two dimensional array with 60 rows and 30 columns and so on.
Int matrix [4][3] = { 1,2,3,4,5,6,7,8,9,10,11,12};
OR
Int matrix [2][3] = {
{1,2,3},
{4,5,6}, }

#include<stdio.h>
main( ){
char names[3][12] = {“Apple”, “Mango”, “Orange”};
char *charptr;
int I;
for(I=0; names[0][I] !=’\0’;I++)
{
printf(names[0] [I]);
printf(“\n”);
printf(names{I]);
strcpy (charptr,names[2]);
printf(charptr);
}

Dynamic Memory Allocation: 
If an array is declared in the program, its size has to be given as constant and is not alterable during runtime.  If a varying amount of memory is required then it has to be allocated at run-time.  This is called Dynamic Memory Allocation.

Pointers are address variables and hence they can be used only after being made to point to some variable.  If a pointer has to be used without assigning it, the address of existing variable, then it has to assigned address of some memory location which will not be used as scratch pad by the program. Data to be operated upon is then stored in this memory location and processed.  This allocation of memory can be done using the dynamic memory allocation functions.  The format of this function malloc( ) is as :
Void *malloc(unsigned size);

This function is declared in header file malloc.h.  it allocated a block of memory to the program of size number of bytes and returns address of the first byte in that block.  This address can be stored in a pointer variable and used to access that block of memory.  Malloc( ) function returns pointer of type void.  If enough memory is not available, it returns a NULL pointer.
char *cptr;
cptr =(char*)malloc(1000);
if (cptr == 0)
{
printf(“not Enough Memory”);
int *iptr;
iptr =(int *)malloc(1000 * size of (int));

In the first example there is an allocation of 1000 bytes to char.  Pointer can be used as a char array and second example allocates 1000 integers to the integer pointer variable and can be declared for an array of 100 integers.
Example:
#include<stdio.h>
void main( )
{
float *figures;
int total, t;
printf(“enter no of figures”);
scanf(“%d”,&total);
figures =((floact*)malloc(total *size of(float));
for(t=0; t<<total; ++t){
printf(“enter figures No %d”,t+1);
scanf(“%d”,&ficures[t]);
}
free(figures);
}

Memory allocated by malloc( ) remains allocated till program terminated or it is explicitly released using another function call from the library called free( ) which can free only dynamically allocated memory and hence requires the same address that was returned by malloc( ) function.

Command Line Arguments:
Arguments can be passed to a function from a function as formal variables, arguments can also be passed to main( )function from the command line.  The arguments are taken as null-terminated char.  Strings on the command line arguments are considered to be delimited by spaces.  All arguments on command line including program name are passed as command line arguments.  The very first argument is the name of the program and then rest of other arguments and they can be passed to main( ) function with argv and argc.

Where arec is an integer variable and contains number of arguments typed at command line argument and argv is array of pointers to characters or pointer to pointer to chracters, each of the character pointer of array argv points to each arguments typed.

# include<stdio.h>
void main(int argc, char *argv[])
{
int x=1;
printf(“Total number of arguments typed = %d”,argc);
printf(“Program name%s \n”,argv[0]);
printf(“Rest of the arguments \n”);
while( s<argc)
{
printf(“%s \n”,argv[x++]);
}

Programs for Chapter 3

Example 1(Finding Big Number using Pointer Variable)

#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main( )
{
clrscr( );
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
printf("\n\n Value of I :  %d",i);
printf("\n Value of j    :  %d",j);
printf("\n Value of k   :  %d",k);
x=&i;
y=&j;
z=&k;
printf("\n\n Original Value in X  %d: ",x);
printf("\n Original Value in Y     %f: ",y);
printf("\n Original Value in Z     %c: ”,z);
x++;
y++;
z++;
printf("\n\n New Value in X   %d: ",x);
printf("\n New Value in Y      %f:  ",y);
printf("\n New Value in Z      %c:  ",k);
getch( );
}

Example 2(Finding Small Number using Pointer Variable)

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main( )
{
clrscr( );
int i,n,small,*ptr,a[50];
printf("\n Enter Size of Array : ");
scanf(%d”,&n);
printf("\n Array Elements      : ");
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
ptr=a;
small = *ptr;
for(i=0;i<n;i++)
{
if(small> *ptr)
{
small= *ptr;
ptr++;
}
}
printf("\n Smallest number  : %d",small);
getch( );
}
Example 3(String Functions)
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
clrscr( );
char name[30];
char surname[30];
char msg[]=" C and C++\n C++ to Java\n Java to....";
printf("\n enter Your name     :");
scanf(“%s”,&name);
printf("\n enter Your Surname     :");
scanf(“%s”,&surname);
printf("\n Length of Your name :%d”,strlen(name));
printf("\t Surname %d",strlen(surname));
printf("\n Your name is        :%s %s“,name,surname);
printf(\n\n Dear %s , %s",name, surname);
printf("\t Please note following message:\n\n");
printf(“%s”,msg);
strcpy(name,surname);
printf("\n\n After String Copy name into surname : %s",surname);
printf("\n............................................");
strcat(name,surname);
printf("\n\n After Concatenating name and surname :  %s",name);
getch( );
}

Example 4(Swapping the values)
#include<conio.h>
#include<stdio.h>
void swap(int &x,int &y);
void main( )
{
clrscr( );
int a,b;
printf("\n Enter a Number             : ");
scanf(“%d”,&a);
printf("\n Enter another number       : ");
scanf(“%d”,&b);
printf("\n Value of X and Y before Exchange  %d,    %d : ",a,b);
swap( a, b);
printf("\n Value of A and B after Exchange  %d,    %d : ",a,b);
getch( );
}
void swap(int &x, int &y){
int t;
t  = x;
x  = y;
y  = t;
}

Example 5(Pyramid)

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(void)
{
char *weirdo ="ABRACADABARA";
int len =strlen(weirdo);
for(int sub =0; sub<=len; ++sub)
cout.write(weirdo,sub)<<"\n";
getch( );
}

Example 6 (String Comparision)

#include<stdio.h>
#include<string.h>
#include<conio.h>
main( ){
clrscr( );
char string[10], string1[10];
int x;
printf("\nEnter the Word: ");
scanf("%s",string);
printf("\nEnter the Word to Compared: ");
scanf("%s",string1);
x = strcmp(string,string1);
if(x==0)
printf("\n They are Similar Words");
else
printf("\nThey are Non-Similar Words");
getch( );
}

Example 7 (Finding Prime Number)

#include<stdio.h>
#include<conio.h>
main( ){
clrscr( );
int num,i;
printf("Enter the number ");
scanf("%d",&num);
i=2;
while(i<=num-1)
{
if(num%i==0)
{
printf("\nNot a Prime Number");
break;
}
i++;
}
if(i==num)
{
printf("Prime Number");
}
getch( );
}

Example 8 (Finding Prime Number between 1 to 100)
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
int i,a,k=1,j=2,res;
printf("\nThe the Prime Numbers from 1 to 100 are........");
printf("\n\nPrime");
for(a=3;a<=100;a++)
{
i=2;
while (i<a)
{
if(res = a%i)==0)
{
break;
}
else
{
i++;
}
}
}
if(res!=0)
printf("\n Prime : %d”,a);
getch( );
}

Example 9(An Array Program)

#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr( );
int a[7]={11,12,13,14,15,16,17};
int i;
printf("\n \nContents of the Array\n ");
for(i=0;i<=6;i++)
{
printf(“%d \t “,a[i]);
}
getch( );
}

Example 10 (Calculating sum and Average in an Array)

#include <stdio.h>
#include<conio.h>
main( )
{
clrscr( );
int sum,avg,i,num[10];
printf("\n Enter any 10 Numbers :");
for(i=0;i<=10;i++){
scanf("%d",&num[i]);
}
sum=0;
for(i=0;i<=10;i++)
{
sum+=num[i];
}
avg=sum/10;
printf("\nThe Sum of 10 Numbers is %d",sum);
printf("\nThe Avarage of 10 Numbers is %d",avg);
getch( );
}

Example 11 ( One Dimensional Array)

#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr( );
int a[10];
int i,n;
printf("\n Numbers in Array ?");
scanf(“%d”,n);
for(i=0;i<=n-1;i++)
{
printf("\n Enter Elements ");
scanf(“%d”,a[i]);
}
printf("\n Contents of the Array ");
printf(“\t %d”,a[i] “\t”);
getch( );
}

Example 12 ( Two Dimensional Array)

#include<stdio.h>
#include<conio.h>
#define N 3
#define M 4
void main(void)
{
clrscr( );
int i,j;
char a[N][M]={
      { 'S','a','n','d'},
      { 'h','y','a','s'},
      { 's','r','e','e'}};
printf("\n    Contents in Array   ");
for(i=0;i<=N-1;++i)
{
for(j=0;j<=M-1;++j)
printf(“%c \n “,a[i][j]<<"   ";
}
getch( );
}

No comments:

Post a Comment