0% found this document useful (0 votes)
72 views

Command Line Arguments

The document discusses pointers in C programming. Some key points: - Pointers store the address of other variables in memory. They can be declared using an asterisk (*) before the variable name. - Pointers allow accessing and modifying the value at a specific memory address. The asterisk (*) operator dereferences a pointer to access the value. - Common pointer operations include assigning addresses using the address-of (&) operator, incrementing/decrementing pointers, passing pointers to functions, and returning pointers from functions. - Other pointer types discussed include null pointers, void pointers, pointers as function arguments, functions returning pointers, pointers to functions, and pointers used with arrays.

Uploaded by

smsaranya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Command Line Arguments

The document discusses pointers in C programming. Some key points: - Pointers store the address of other variables in memory. They can be declared using an asterisk (*) before the variable name. - Pointers allow accessing and modifying the value at a specific memory address. The asterisk (*) operator dereferences a pointer to access the value. - Common pointer operations include assigning addresses using the address-of (&) operator, incrementing/decrementing pointers, passing pointers to functions, and returning pointers from functions. - Other pointer types discussed include null pointers, void pointers, pointers as function arguments, functions returning pointers, pointers to functions, and pointers used with arrays.

Uploaded by

smsaranya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

POINTERS

The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to
another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous
memory location. The purpose of pointer is to save memory space and achieve faster execution time.

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer
used to dereference a pointer.

Syntax

data_type * pointer_variable_name;

Here,

 data_type is the pointer's base type of C's variable types and indicates the type of the variable that
the pointer points to.

 The asterisk (*: the same asterisk used for multiplication) which is indirection operator, declares a
pointer.

Example

int *a;//pointer to int  
char *c;//pointer to char

A simple program for pointer illustration is given below:

#include <stdio.h>

int main()

int a=10; //variable declaration

int *p; //pointer variable declaration

p=&a; //store address of variable a in pointer p

printf("Address stored in a variable p is:%x\n",p); //accessing the address

printf("Value stored in a variable p is:%d\n",*p); //accessing the value

return 0;

}
Output:

Address stored in a variable p is:60ff08

Value stored in a variable p is:10

Example 2

#include <stdio.h>

int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer

printf("%d\n", *p); //this will print the value of 'a'

printf("%d\n", *&a); //this will also print the value of 'a'

printf("%u\n", &a); //this will print the address of 'a'

printf("%u\n", p); //this will also print the address of 'a'

printf("%u\n", &p); //this will print the address of 'p'

return 0;
}
Output
10                                                                                   
10                                                                                   
1191181796                                                                           
1191181796                                                                           
1191181800

Points to remember while using pointers

1. While declaring/initializing the pointer variable, * indicates that the variable is a pointer.


2. The address of any variable is given by preceding the variable name with Ampersand &.
3. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is
going to contain an integer value. It means that a is going to contain the address of a variable
storing integer value.
4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can be
read as 'value at'.
Operator Meaning

* Serves 2 purpose

1. Declaration of a pointer

2. Returns the value of the


referenced variable

& Serves only 1 purpose

 Returns the address of a variable

Types of Pointers in C

Following are the different Types of Pointers in C:

Null Pointer

We can create a null pointer by assigning null value during the pointer declaration. This method is useful
when you do not have any address assigned to the pointer. A null pointer always contains value 0.

Following program illustrates the use of a null pointer:

#include <stdio.h>

int main()

int *p = NULL; //null pointer

printf(“The value inside variable p is: %d”,p);

return 0;

Output:

The value inside variable p is:

Void Pointer

In C programming, a void pointer is also called as a generic pointer. It does not have any standard data
type. A void pointer is created by using the keyword void. It can be used to store an address of any
variable.
Following program illustrates the use of a void pointer:

#include <stdio.h>

int main()

void *p = NULL; //void pointer

printf("The size of pointer is:%d\n",sizeof(p));

return 0;

Output:

The size of pointer is:8

Direct and Indirect Access Pointers

In C, there are two equivalent ways to access and manipulate a variable content

 Direct access: we use directly the variable name

 Indirect access: we use a pointer to the variable

Let's understand this with the help of program below

#include <stdio.h>

/* Declare and initialize an int variable */

int var = 1;

/* Declare a pointer to int */

int *ptr;

int main( void )

/* Initialize ptr to point to var */

ptr = &var;

/* Access var directly and indirectly */

printf("\nDirect access, var = %d", var);

printf("\nIndirect access, var = %d", *ptr);


/* Display the address of var two ways */

printf("\n\nThe address of var = %d", &var);

printf("\nThe address of var = %d\n", ptr);

/*change the content of var through the pointer*/

*ptr=48;

printf("\nIndirect access, var = %d", *ptr);

return 0;}

Output

Direct access, var = 1

Indirect access, var = 1

The address of var = 6295616

The address of var = 6295616

Indirect access, var = 48

Pointers as Function Argument in C

Pointer as a function parameter is used to hold addresses of arguments passed during function call. This is
also known as call by reference. When a function is called by reference any change made to the reference
variable will effect the original variable.

Example Time: Swapping two numbers using Pointer

#include <stdio.h>

void swap(int *a, int *b);

int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);

swap(&m, &n); //passing address of m and n to the swap function


printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output
m = 10
n = 20
After Swapping:
m = 20
n = 10

Functions returning Pointer variables


A function can also return a pointer to the calling function. In this case you must be careful, because local
variables of function doesn't live outside the function. They have scope only inside the function. Hence if
you return a pointer connected to a local variable, that pointer will be pointing to nothing when the function
ends.

#include <stdio.h>

int* larger(int*, int*);

void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}

int* larger(int *x, int *y)


{
if(*x > *y)
return x;
else
return y;
}

Output
92 is larger
Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as an argument in another
function. A pointer to a function is declared as follows,
Syntax: type (*pointer-name)(parameter);
Here is an example :

 int (*sum)(); //legal declaration of pointer to function


 int *sum(); //This is not a declaration of pointer to function
A function pointer can point to a specific function when it is assigned the name of that function.
int sum(int, int);
int (*s)(int, int);
s = sum;
Here s is a pointer to a function sum. Now sum can be called using function pointer s along with providing
the required argument values.
s (10, 20);
Example of Pointer to Function
#include <stdio.h>

int sum(int x, int y)


{
return x+y;
}

int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);

return 0;
}

Output

Sum is 25
Pointer to a Pointer in C(Double Pointer)
Pointers are used to store the address of other variables of similar datatype. But if you want to store the
address of a pointer variable, then you again need a pointer to store it. Thus, when one pointer variable
stores the address of another pointer variable, it is known as Pointer to Pointer variable or Double
Pointer.
Syntax:
int **p1;

Simple program to represent Pointer to a Pointer


#include <stdio.h>

int main() {

int a = 10;
int *p1; //this can store the address of variable a
int **p2;

p1 = &a;
p2 = &p1;

printf("Address of a = %u\n", &a);


printf("Address of p1 = %u\n", &p1);
printf("Address of p2 = %u\n\n", &p2);

// below print statement will give the address of 'a'

printf("Value at the address stored by p2 = %u\n", *p2);

printf("Value at the address stored by p1 = %d\n\n", *p1);

printf("Value of **p2 = %d\n", **p2); //read this *(*p2)

return 0;
}

Output
Address of a = 2686724
Address of p1 = 2686728
Address of p2 = 2686732
Value at the address stored by p2 = 2686724
Value at the address stored by p1 = 10
Value of **p2 = 10
Pointer and Arrays in C
When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of
the array. Base address i.e address of the first element of the array is also allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be
stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the first element of the
array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name
of the array and it acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.

[NOTE: Now we can access every element of the array arr using p++ to move from one element to
another.]

Example program

#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("\n%d", *p);
p++;
}

return 0;
}
Output
12345

Access Array Elements Using Pointers


#include <stdio.h>
int main() {
int data[5];

printf("Enter elements: ");


for (int i = 0; i < 5; ++i)
scanf("%d", data + i);

printf("You entered: \n");


for (int i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}
Output
Enter elements: 1
2
3
4
5
You entered:
1
2
3
4
5

Note

Then, the elements of the array are accessed using the pointer notation. By the way,
 data[0] is equivalent to *data and &data[0] is equivalent to data
 data[1] is equivalent to *(data + 1) and &data[1] is equivalent to data + 1
 data[2] is equivalent to *(data + 2) and &data[2] is equivalent to data + 2
 ...
 data[i] is equivalent to *(data + i) and &data[i] is equivalent to data + i

Pointer and Character strings

Pointer can also be used to create strings. Pointer variables of char type are treated as string.

char *str = "Hello";

Example program

#include <stdio.h>

int main()
{
char *str = "Hello welcome";
printf("%s",str);

return 0;
}
Output
Hello welcome

Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know
that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be
a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an
integer value. Following arithmetic operations are possible on the pointer in C language:

 Increment
 Decrement
 Addition
 Subtraction
 Comparison

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by the size
of the data type to which the pointer is pointing.

The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type)  

Where i is the number by which the pointer get increased.

32-bit-For 32-bit int variable, it will be incremented by 2 bytes.

64-bit-For 64-bit int variable, it will be incremented by 4 bytes.

Let's see the example of incrementing pointer variable on 64-bit architecture.

#include<stdio.h>  
int main(){  
int number=50;        
int *p;//pointer to int      
p=&number;//stores the address of number variable        
printf("Address of p variable is %u \n",p);        
p=p+1;        
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 b
ytes.      
return 0;  
}    
Output
Address of p variable is 4063936196                                                  
After increment: Address of p variable is 4063936200

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to the
previous location. The formula of decrementing the pointer is given below:

new_address= current_address - i * size_of(data type)  

32-bit -For 32-bit int variable, it will be decremented by 2 bytes.

64-bit-For 64-bit int variable, it will be decremented by 4 bytes.

Let's see the example of decrementing pointer variable on 64-bit OS.

#include <stdio.h>            

void main(){            

int number=50;        

int *p;//pointer to int      

p=&number;//stores the address of number variable        

printf("Address of p variable is %u \n",p);        

p=p-1;       

printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate previo
us location.         

}      

Output

Address of p variable is 3184874404                                                  

After decrement: Address of p variable is 3184874400

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

1. new_address= current_address + (number * size_of(data type))  

32-bit-For 32-bit int variable, it will add 2 * number.


64-bit-For 64-bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64-bit architecture.

#include<stdio.h>  

int main(){  

int number=50;        

int *p;//pointer to int      

p=&number;//stores the address of number variable        

printf("Address of p variable is %u \n",p);        

p=p+3;   //adding 3 to pointer variable    

printf("After adding 3: Address of p variable is %u \n",p);       

return 0;  

}    

Output

Address of p variable is 3214864300

After adding 3: Address of p variable is 3214864312

As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e.,
4*3=12 increment. Since we are using 64-bit architecture, it increments 12. But if we were using 32-bit
architecture, it was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit
OS.

C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a
pointer will give an address. The formula of subtracting value from the pointer variable is given below:

new_address= current_address - (number * size_of(data type))  

32-bit-For 32-bit int variable, it will subtract 2 * number.

64-bit-For 64-bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from the pointer variable on 64-bit architecture.

#include<stdio.h>  
int main(){  

int number=50;        

int *p;//pointer to int      

p=&number;//stores the address of number variable        

printf("Address of p variable is %u \n",p);        

p=p-3; //subtracting 3 from pointer variable    

printf("After subtracting 3: Address of p variable is %u \n",p);        

return 0;  

}    

Output

Address of p variable is 3214864300

After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address value.

Multidimensional Array

In multidimensional array, the first array size does not have to be specified. The second (and any
subsequent) dimensions must be given.

Example

int (*arr) [ ][10]

Now we know two dimensional array is array of one dimensional array. Hence let us see how to access a
two dimensional array through pointer.

Let us suppose a two-dimensional array

int matrix[3][3];

For the above array,


matrix => Points to base address of two-dimensional array.
Since array decays to pointer.

*(matrix) => Points to first row of two-dimensional array.


*(matrix + 0) => Points to first row of two-dimensional array.
*(matrix + 1) => Points to second row of two-dimensional array.
**matrix => Points to matrix[0][0]
*(*(matrix + 0)) => Points to matrix[0][0]
*(*(matrix + 0) + 0) => Points to matrix[0][0]
*(*matrix + 1) => Points to matrix[0][1]
*(*(matrix + 0) + 1) => Points to matrix[0][1]
*(*(matrix + 2) + 2) => Points to matrix[2][2]

Example Program 1
#include <stdio.h>
int main(void)
{
// 2d array
int aiData [3][3] = { { 9, 6, 1 }, { 14, 70, 50 }, {10, 12, 78} };
int *piData = NULL; //pointer to integer
int i,j;
piData = &aiData[0][0]; //You can also write *aiData
for (i = 0; i < 3; ++i) //Loop of row
{
for (j = 0; j < 3; ++j)// Loop for coloum
{
//Read element of 2D array
// *(piData + ( i * 3) + j) is equivalent to &matrix[i][j]
printf("aiData[%d][%d] = %d\n",i,j, *(piData + ( i * 3) + j));
}
}
return 0;
}
Output
aiData[0][0] = 9                                                                     
aiData[0][1] = 6                                                                     
aiData[0][2] = 1                                                                     
aiData[1][0] = 14                                                                    
aiData[1][1] = 70                                                                    
aiData[1][2] = 50                                                                    
aiData[2][0] = 10                                                                    
aiData[2][1] = 12                                                                    
aiData[2][2] = 78

Example Program 2
#include <stdio.h>
#define ROWS 3
#define COLS 3
/* Function declaration to input and print two dimensional array */
void inputMatrix(int matrix[][COLS], int rows, int cols);
void printMatrix(int matrix[][COLS], int rows, int cols);
int main()
{
int matrix[ROWS][COLS];
int i, j;
/* Input elements in matrix */
printf("Enter elements in %dx%d matrix.\n", ROWS, COLS);
inputMatrix(matrix, ROWS, COLS);
/* Print elements in matrix */
printf("Elements of %dx%d matrix.\n", ROWS, COLS);
printMatrix(matrix, ROWS, COLS);
return 0;
}
/**
* Function to take input in two dimensional array (matrix)
* from user.
*/
void inputMatrix(int matrix[][COLS], int rows, int cols)
{
int i, j;
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
// (*(matrix + i) + j is equivalent to &matrix[i][j]
scanf("%d", (*(matrix + i) + j));
}
}
}
void printMatrix(int (*matrix)[COLS], int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
// *(*(matrix + i) + j) is equivalent to matrix[i][j]
printf("%d ", *(*(matrix + i) + j));
}
printf("\n");
}
}
Output
Enter elements in 3x3 matrix.
123
456
789
Elements of 3x3 matrix.
123
456
789

Note: You can use any of the two notations int matrix[][COLS] or int (*matrix)[COLS], to access two
dimensional array using pointers. The first int matrix[][COLS] is general array notation. Whereas int
(*matrix)[COLS]  is a pointer to array.

Command Line Arguments


 Argument is input values or input elements.
 Command line- It is CUI(Command User Interface) or Character user interface.
Example DOC operating system.
Blue screen called as Integrated development Environment (IDE)
OS

CUI GUI
(Programmer) (End user)
 Programmer works with CUI.
Working of CUI
1. Open note pad & write a program
2. Open DOS & locate the compiler ->tcc.exe
3. Compile source program
4. Run program
Short cuts
 Save-F2
 Compile-Alt+F9
 Run –Ctrl+F9
 O/P-Alt+F5
How to pass argument in Command line
Cmd/> tcc.exe sample.c
->Generate sample.exe file
Cmd/> sample.exe 1 2 3 4

Example Program
#include <stdio.h>

int main( int argc, char *argv [] )


{
printf(" \n Name of my Program %s \t", argv[0]);

if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc > 2 )
{
printf("\n Many values given by users.\n");
}
else
{
printf(" \n Single value expected.\n");
}
}
#include <stdio.h>

int main( int argc, char *argv [] )


{
printf(" \n Name of my Program %s \t", argv[0]);

if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc > 2 )
{
printf("\n Many values given by users.\n");
}
else
{
printf(" \n Single value expected.\n");
}
}

Complicated declarations in C
Most of the times declarations are simple to read, but it is hard to read some declarations which involve
pointer to functions.

The steps to read complicated declarations.

1) Convert C declaration to postfix format and read from right to left.


2) To convert expression to postfix, start from innermost parenthesis, If innermost parenthesis is not
present then start from declarations name and go right first. When first ending parenthesis encounters then
go left. Once whole parenthesis is parsed then come out from parenthesis.
3) Continue until complete declaration has been parsed.

 Rules:

 Always read declarations from the inside out: Start from the innermost, if any, parenthesis.
Locate the identifier that's being declared, and start deciphering the declaration from there.

 When there is a choice, always favor [] and () over *: If * precedes the identifier and [] follows it,
the identifier represents an array, not a pointer. Likewise, if * precedes the identifier and () follows
it, the identifier represents a function, not a pointer. (Parentheses can always be used to override the
normal priority of [] and () over *.)

Example 1:
int *a[10];

Applying rule:

int *a[10]; "a is"


^

int *a[10]; "a is an array"


^^^^

int *a[10]; "a is an array of pointers"


^

int *a[10]; "a is an array of pointers to `int`".


^^^

The complex declaration like:

void ( *(*f[]) () ) ();

by applying the above rules:

void ( *(*f[]) () ) (); "f is"


^

void ( *(*f[]) () ) (); "f is an array"


^^

void ( *(*f[]) () ) (); "f is an array of pointers"


^
void ( *(*f[]) () ) (); "f is an array of pointers to function"
^^

void ( *(*f[]) () ) (); "f is an array of pointers to function returning pointer"


^

void ( *(*f[]) () ) (); "f is an array of pointers to function returning pointer to function"
^^

void ( *(*f[]) () ) (); "f is an array of pointers to function returning pointer to function returning `void`"
^^^^

You might also like