Pointer
Pointer
CHAPTER XI
POINTERS
11.1 INTRODUCTION
• A pointer is a derived data type in c. (iv) Pointers are helpful in traversing through
arrays and character strings. The strings
• Pointers contains memory addresses as
are also arrays of characters terminated by
their values.
the null character (‘\0’).
• A pointer is a variable whose value is the
(v) Pointers also act as references to different
address of another variable, i.e., direct
types of objects such as variables, arrays,
address of the memory location.
functions, structures, etc. In C, we use
• Like any variable or constant, you must pointer as a reference.
declare a pointer before using it to store
(vi) Storage of strings through pointers saves
any variable address.
memory space.
• Pointers can be used to access and
(vii) Pointers may be used to pass on arrays,
manipulate data stored in the memory.
strings, functions, and variables as
Advantages arguments of a function.
(i) Pointers make the programs simple and (viii) Passing on arrays by pointers saves lot of
reduce their length. memory because we are passing on only
(ii) Pointers are helpful in allocation and de- the address of array instead of all the
allocation of memory during the execution elements of an array, which would mean
of the program. passing on copies of all the elements and
Thus, pointers are the instruments thus taking lot of memory space.
dynamic memory management. (ix) Pointers are used to construct different
(iii) Pointers enhance the execution speed of a data structures such as linked lists, queues,
program. stacks, etc.
11.2 ACCESSING THE ADDRESS VARIABLE
• The operator & immediately preceding a #include <stdio.h>
variable returns the address of the variable #include <conio.h>
associated with it. void main()
Example {
p=&quantity; int x=125;
• Would assign 5000 (the location of float p=20.345;
quantity) to the variable p.
char a=‘a’;
• The & operator is a address operator.
clrscr();
• The & operator can be used only with a
simple variable or an array element. printf(“%d is stored at addr %u\n”,x,&x);
&125 pointing at constants printf(“%f is stored at addr %u\n”,p,&p);
int x[10]; illegal printf(“%c is stored at addr %u\n”,a,&a);
&x pointing at array names getch();
&(x+y) pointing at expressions }
• If x is an array then expression such as
&x[0] is valid.
DECLARING POINTER VARIABLES INITIALIZATION OF POINTER
Syntax VARIABLES
data_type *pt_name; • The process of assigning the address of a
variable to a pointer variable is known as
1. The * tells that the variable pt_name is a
initialization.
name of the pointer variable.
• All uninitialized pointers will have some
2. Pt_name needs a memory location.
unknown values that will be interpreted as
3. Pt_name points to a variable of type memory addresses.
data_type.
• They may not be valid addresses or they
Example may point to some values that are wrong.
int *p; • Once a pointer variable has been declared
• Declares the variable p as a pointer we can use the assignment operator to
variable that points to an integer data type. initialize the variable.
• The declarations cause the compiler to Example
alocate memory locations for the pointer 1. int q; 2. int q; 3. int x,*p=&x
variable p. int *p; int *p=&q
p=&q;
Illegal statement int *p=&x, x;
• We can also define a pointer variable with
an initial value to NULL or 0.
int *p=null:
int *p=0;
11.3 POINTER FLEXIBILITY
• Pointers are flexible.
• We can make the same pointer to point to different data variables in different statements.
Example
int x, y, z, *p
……………
*p=&x;
……………
*p=&y;
……………
*p=&z;
……………
• We can also use different pointers to point to the same data variable.
Example
int x;
int *p1=&x;
int *p2=&x;
int *p3=&x;
…………..
• With the exception of NULL and 0, no other constant value can be assigned to a pointer variable.
11.4 ACCESSING A VARIABLE THROUGH ITS
POINTERS
#include <stdio.h>
• We can access the value of another
variable using the pointer variable. int main(void)
{
Steps: //normal variable
• Declare a normal variable, assign the int num = 100;
value.
• Declare a pointer variable with the //pointer variable
same type as the normal variable. int *ptr;
• Initialize the pointer variable with the //pointer initialization
address of normal variable.
• Access the value of the variable by ptr = #
using asterisk (*) - it is known //pritning the value
as dereference operator (indirection
operators). printf("value of num = %d\n", *ptr);
return 0;
}
EXAMPLE
#include <stdio.h> Output
void main() Value of x is 10
{
int x,y; 10 is stored at address 2996846848
int *ptr; 10 is stored at address 2996846848
x=10; 10 is stored at address 2996846848
ptr=&x;
298120448 is stored at address 2996846856
y=*ptr;
printf("Value of x is %d\n",x);
10 is stored at address 2996846852
printf("%d is stored at address %u\n",x,&x);
printf("%d is stored at address %u\n",*&x, &x);
New value of x =100
printf("%d is stored at address %u\n",*ptr,ptr);
printf("%d is stored at address %u\n",ptr,&ptr);
printf("%d is stored at address %u\n",y,&y);
*ptr=100;
printf("\nNew value of x =%d\n",x);
}
ILLUSTRATION OF POINTER EXPRESSION
Stage values in the storage cells and their address
x y ptr
Declaration
address
y=*ptr 10 10 2996846848
address
pointer to x
char 1 byte
int 2 bytes
float 4 bytes
long int 4 bytes
double 8 bytes
11.8 POINTERS AND ARRAYS
• The address of &x[0] and x is the same. It's for(i = 0; i < n; ++i)
because the variable name x points to the first {
element of the array. /* Equivalent to scanf("%d", &x[i]); */
• &x[0] is equivalent to x. And, x[0] is equivalent scanf("%d", x+i);
to *x. // Equivalent to sum += x[i]
• Similarly, &x[1] is equivalent to x+1 and x[1] is sum += *(x+i);
equivalent to *(x+1). }
• &x[2] is equivalent to x+2 and x[2] is equivalent printf("Sum = %d", sum);
to *(x+2). return 0;
• Basically, &x[i] is equivalent to x+i and x[i] is }
equivalent to *(x+i). Output
Enter the value of n: 5
Example 1: Pointers and Arrays Enter number one by one
5
#include <stdio.h> 10
int main() 15
{ 20
int i, x[20], sum = 0,n; 25
Sum = 75
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter number one by one\n");
Example :2 output
#include <stdio.h> Enter the value of n
int main()
5
{
Enter the array elements one by one
int *p,sum,i;
int n,x[10]; 1
printf ("Enter the value of n\n"); 2
scanf("%d",&n); 3
printf("Enter the array elements one by one\n"); 4
for (i=0;i<n;i++) 5
scanf("%d",&x[i]); Elements Value Address
p=x;
printf("Elements\t Value\t Address\n"); x[0]
for (i=0;i<n;i++) 1 2316341728
{ x[1] 2 2316341732
printf("x[%d] %d %u\n",i,*p,p);
sum +=*p; x[2] 3 2316341736
p++;
} x[3] 4 2316341740
printf("\n Sum = %d",sum);
x[4] 5 2316341744
printf("\n address of first element (&x[0]) =
%u",&x[0]);
Sum = 16
printf("\n p = %u",p);
address of first element (&x[0]) = 2316341728
return 0;
}
p = 2316341748
• Pointers can be used to manipulate two-dimensional arrays also.
• An two-dimensional array can be represented by the pointer expression as follows
• *(*(a+i)+j) or *(*(p+1)+j)
COLUMNS
0 1 2 3 4 5
0 p
1 p+1
R
2 p+2
O 3
W
S 4 4,0 4,3 p+4
5
6 p+6
*(p+4) *(p+4)+3
p pointer to first row
p+i pointer to ith row printf("\n\n");
*(p+i) pointer to first element in the ith row }
*(p+i) +j pointer to jth element in the ith // signal to operating system program ran fine
row return 0;
*(*(p+i)+j) valu stored in the ith row and }
jth columns. Output
Example arr[2][3]=44Address of 0 th array 2692284448
#include<stdio.h> arr[0][0]=11
int main() arr[0][1]=22
{ arr[0][2]=33
int arr[3][4] = { {11,22,33,44}, arr[0][3]=44
{55,66,77,88},{11,66,77,44}}; Address of 1 th array 2692284464
int i, j; arr[1][0]=55
for(i = 0; i < 3; i++) arr[1][1]=66
{ arr[1][3]=88
printf("Address of %d th array %u \n",i , *(arr + i)); Address of 2 th array 2692284480
for(j = 0; j < 4; j++) arr[2][0]=11
{
arr[2][1]=66
printf("arr[%d][%d]=%d\n", i, j, *( *(arr + i) + j) );
arr[2][2]=77
}
arr[2][3]=44
11.9 POINTERS AND CHARACTER STRINGS
• C supports an alternate method to create #include <stdio.h>
strings using pointer variables of type #include <string.h>
char. int main ()
Example {
char *str= “Hello”; char name[25];
• This creates a string for the literal and then char *ptr;
stores its address in the pointer variable strcpy(name,"gaccbe");
str. ptr=name;
• The pointer str now points to the first while(*ptr !='\0')
character of the string “Hello” as {
printf("\n %c is stored at address %u",*ptr,ptr);
ptr++;
H e l l o \0 }
return 0;
}
str Output
g is stored at address 3432464000
2. High-level i/o and uses functions in C’s fputs ( ) write a string into a file
standard library. fgets ( ) read a string from a file
fread() read an entire record from a file
fwrite() write an entire record into a file
12.2 DEFINING AND OPENING A FILE
• To store data in a file in the secondary 1. fp as a file pointer to the data type FILE.
memory, we must specify 2. Filename- the file opened in the named
1. Filename filename and assign an identifier to the
FILE type pointer fp.
2. Data structure
3. Mode- It is a string (usually a single
3. Purpose
character ) that specifies the mode in
• file_name − It is a string that specifies the which the file is to be opened.
name of the file that is to be opened or
“r” − open for reading
created using the fopen method.
“rb” − open for reading in binary mode
It may contain two parts
“w” − open for writing only
A primary name and an optional period
with the extension. “wb” − open for writing in binary mode
• Data structure of a file is defined as FILE “a” − open for append only
in the library of standard I/O functions “ab” − open for append in binary
definition. “r+” − open for reading and writing both
• Purpose-what we want to do with the file. “rb+” − open for reading in binary mode
Example “w+” − open for writing and reading
FILE *fp; “wb+” - open for writing and reading in
fp = fopen(“file_name”, “mode”); binary mode
“a+” − open for read and append
“ab+” − open for read and append in binary
12.3 CLOSING A FILE
• A file must be closed as soon as the all • Once the file is closed, its file pointer can
operations are completed. be reused for another file.
fclose(file_pointer); • All files are closed automatically
• Close file associated with the FILE pointer whenever a program terminates.
file_pointer.
Example
----------
----------
FILE *fp1,*fp2;
fp1=fopen(“INPUT”,”w”);
fp2=fopen(“OUTPUT”,”r”);
----------
----------
fclose(fp1);
fclose(fp2);
12.4 INPUT/OUTPUT OPERATIONS ON FILES
The getc() and putc() function #include <stdio.h>
• The file is opened with mode w and int main()
filepointer fp1. {
putc(c,fp1); FILE *fp;
• Writes a character contained in the char c;
character variable c to the file associated printf("Data Input\n");
with FILE pointer fp1.
fp=fopen("INPUT.TXT","w");
c=getc(fp2);
while ((c=getchar()) != EOF)
• Reads a character from the file whose file
pointer is fp2. putc(c,fp);
• The file pointer moves by one character fclose(fp);
position for every operations of getc() and printf("Data Output\n");
putc(). fp=fopen("INPUT.TXT","r");
Example while ((c=getc(fp))!=EOF)
printf("%c",c);
fclose(fp);
return 0;
}
get() and putw() functions printf("Data Output\n");
• Integer oriented functions. f1=fopen("DATA.TXT","r");
• Used to read and write integer values. while ((n=getw(f1))!=EOF)
putw(integer,fp); printf("%d",n);
integer_variable=getw(fp); fclose(f1);
Example return 0;
#include <stdio.h> }
int main() Output
{ Data file
FILE *f1; 1
int n,i; 2
printf("Data file\n"); 3
f1=fopen("DATA.TXT","w"); 4
for (i=1;i<=10;i++) 5
{ 6
scanf("%d",&n); -1
if(n== -1) break; Data Output
putw(n,f1); 1 2 3 4 5 6
} .
fclose(f1);
fscanf() and fprintf() functions
printf("Item Name no price Quantity\n");
• These functions are used performed I?O for(i=1;i<=3;i++)
operations on files.
{
fprintf(fp,”control string”,list); scanf("%s %d %f %d", item, &n, &price, &qty);
fscanf(fp,control string”,list); fprintf(fp,"%s %d %f %d",item,n,price,qty);
• Where fp is a file pointer associate with a }
file that has been opened for writing. fclose(fp);
• The control string contains output printf("Data Output\n");
specifications for the items in the list. fp=fopen(filename,"r");
• The list may include variables, constants printf("Item Name no price Quantity\n");
and strings. for(i=1;i<=3;i++)
Example {
fscanf(fp,"%s %d %f %d",item,&n,&price,&qty);
#include <stdio.h>
printf("%s %d %f %d\n",item,n,price,qty);
int main()
}
{ fclose(fp);
FILE *fp; int n,qty,i; return 0;
float price,value; }
char item[10],filename[10]; Output
printf("Input file name\n");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("input inventory details\n");
Output
note
1
50.50
100
pencil
2
56.90
290
paper
3
120.00
500
Data Output
Item Name no price Quantity
10
20
30
40
50
60
70
80
90
100
12.6 RANDOM ACCESS FILE
• functions for random access file
processing. value meaning
1. fseek() 0 Beginning of the file
2. ftell() 1 Current position
3. rewind()
2 End of the file
fseek()
This function is used for seeking the .
pointer position in the file at the specified
Statement Meaning
byte.
Syntax fseek(fp,0l,0); Got o the beginning
fseek( file_ptr, offset, position); fseek(fp,0l,1); Stay at the current position
file_ptr :pointer to the file concerned.
fseek(fp,0l,2); Go to the end of the file
offset: is a number or variale of type long.
fseek(fp,m,0); Move to (m+1)th byte in the
the no. positions (bytes) to be moved
file
from the location specified by position.
fseek(fp,m,1); Go forward by m bytes
position: is an integer number.
The position can take one of the three values. fseek(fp,-m10); Go backward by m bytes
from the current position
The offset may be positive, meaning move
fseek(fp,-m,2); Go backward by m bytes
forwards, or negative, meaning move
from the end
backwards
Example printf("\nThe current position of the file
#include <stdio.h> pointer is: %ld\n", ftell(fp));
int main () rewind(fp);
{ printf("The current position of the file pointer
FILE *fp; is: %ld\n", ftell(fp));
int c; printf("After rewrite the contents\n");
fp = fopen("OUTPUT.txt","w+"); printf("Read the Random Access File\n");
fputs("Random Access file example", fp); while(1)
fseek( fp, 0, SEEK_SET ); {
printf("Random Access file contains\n"); c = fgetc(fp);
while(1) if( feof(fp))
{ {
c = fgetc(fp); break;
if( feof(fp)) }
{ printf("%c", c);
break; }
} fclose(fp);
printf("%c", c); return(0);
} }
fputs("\nC Programming E Balagurusamy", fp);
fputs("\nsecond edition", fp);
Output
Random Access file contains
Random Access file example
The current position of the file pointer is: 70
The current position of the file pointer is: 0
After rewrite the contents
Read the Random Access File
Random Access file example
C Programming E Balagurusamy
second edition
12.7 COMMAND LINE ARGUMENTS
What is a command line argument? #include <stdio.h>
void main( int argc, char *argv[] )
• It is a parameter supplied to a program when the
{
program is invoked. FILE *fp;
• This parameter may represent a filename the int i;
program should process. Char word[15];
• The command line arguments are handled using fp=fopen(argv[1],"w");
main() function arguments where argc refers to printf("No. of arguments in command line =%d\n",argc);
for(i=2;i<argc;i++)
the number of arguments passed, and argv[] is a
{
pointer array which points to each argument
fprintf(fp,"%s",argv[1]);
passed to the program. }
• In order to access the command line arguments, fclose(fp);
we must declare the main() function and its printf("contents of %s file \n",argv[1]);
parameters are fp=fopen(argv[1],"r");
main(int argc,char *argv[]) for(i=2;i<argc;i++)
{
{ fscanf(fp,"%s",word);
------------- printf("%s",word);
------------- }
fclose(fp);
}
printf("\n\n");
for(i=0;i<argc;i++)
printf("%s\n",argv[i]);
}
References
1. 1. E. Balagurusamy, ”Programming in ANSI C”, Seventh Edition, McGraw Hill Education
India Private Ltd, 2017.
2. . https://www.tutorialspoint.com/cprogramming/
3. https://ecomputernotes.com/what-is-c/function-a-pointer/advantages-of-using-pointers
4. https://www.includehelp.com/c/accessing-the-value-of-a-variable-using-pointer-in-c.aspx
5. https://www.programiz.com/c-programming/c-pointers-arrays
6. https://www.studytonight.com/c/pointer-with-function-in-c.php