0% found this document useful (0 votes)
4 views37 pages

Understanding C Functions and Usage

The document provides an overview of C functions, including their advantages, declaration, calling methods, and definitions. It explains different types of parameters, local and global variables, storage classes, and recursion in C programming. Additionally, it highlights the use of library functions and header files in C, as well as the concepts of call by value and call by reference.

Uploaded by

MALARMANNAN A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views37 pages

Understanding C Functions and Usage

The document provides an overview of C functions, including their advantages, declaration, calling methods, and definitions. It explains different types of parameters, local and global variables, storage classes, and recursion in C programming. Additionally, it highlights the use of library functions and header files in C, as well as the concepts of call by value and call by reference.

Uploaded by

MALARMANNAN A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Functions

In c, we can divide a large program into the basic building blocks known as function. The function contains the
set of programming statements enclosed by { }. A function can be called multiple times to provide reusability
and modularity to the C program. In other words, we can say that the collection of functions creates a program.

Advantage of functions in C

There are the following advantages of C functions.

 By using functions, we can avoid rewriting same logic/code again and again in a program.
 We can call C functions any number of times in a program and from any place in a program.
 We can track a large C program easily when it is divided into multiple functions.
 Reusability is the main achievement of C functions.
 However, Function calling is always a overhead in a C program.

FUNCTION DECLARATION, FUNCTION CALL AND FUNCTION DEFINITION:

There are 3 aspects in each C function. They are,

 Function declaration or prototype – This informs compiler about the function name, function parameters
and return value’s data type.

 Function call – This calls the actual function

 Function definition – This contains all the statements to be executed.

C functions aspects syntax

Return_type function_name (arguments list)


function definition { Body of function; }

function call function_name (arguments list);

function declaration return_type function_name (argument list);

PARAMETERS

Parameters provide the data communication between the calling function and called function. There are two
types of parameters.

Actual Parameters-These are the parameters transferred from the calling program(main program) to the called
program.

Formal Parameters-These are the parameters transferred into the calling function(main program) from the called
program(function)
Example Program

#include<stdio.h>
// function declaration
int sum(int x, int y);

int main()
{
// function call
printf("sum = %d", sum(10, 10));

// signal to operating system everything works fine


return 0;
}
// function definition
int sum(int x, int y)
{
int s;
s = x + y;
return s;
}
Output
Sum=20
Example Program 2
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here

int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}

float square ( float x ) // function definition


{
float p ;
p=x*x;
return ( p ) ;
}

OUTPUT:
Enter some number for finding square

Square of the given number 2.000000 is 4.000000

Local and Global Variables

#include<stdio.h>
int i=10; -> Global Declaration
int main()
{
int j; ->Local Declaration
int fun(); // function declaration
printf("value of i in main : %d\n",i);
fun(); // function call
printf("value of function call : %d",i);
return 0;
}
int fun() // function definition
{
int k;
i=50;
return i;
}
Output
Value of i in main : 10
Value of function call : 50

Different aspects of function calling (Parameter Passing method)

A function may or may not accept any argument. It may or may not return any value. Based on these facts, There are
four different aspects of function calls.

1. function without arguments and without return value


2. function without arguments and with return value
3. function with arguments and without return value
4. function with arguments and with return value

NOTE:
 If the return data type of a function is “void”, then, it can’t return any values to the calling function.
 If the return data type of the function is other than void such as “int, float, double etc”, then, it can return values
to the calling function.
C functions aspects syntax
function declaration:
int function ( int );
function call:
function ( a );
function definition:
1. With arguments and with return values
int function( int a )
{
statements;
return a;
}
function declaration:
void function ( int );
function call: function( a );
function definition:
2. With arguments and without return values
void function( int a )
{
statements;
}
function declaration:
void function();
function call: function();
3. Without arguments and without function definition:
return values void function()
{
statements;
}
function declaration:
int function ( );
function call: function ( );
function definition:
4. Without arguments and with
int function( )
return values
{
statements;
return a;
}

Example for Function without argument and without return value

#include<stdio.h>
void sum();
void main()
{
printf("\n Calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Calculate the sum of two numbers:
Enter two numbers 10 24
The sum is 34

Example for Function without argument and with return value

#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers 10 24
The sum is 34

Example for Function with argument and without return value

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output

Going to calculate the sum of two numbers:


Enter two numbers 10 24
The sum is 34

Example for Function with argument and with return value

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

Output
Going to calculate the sum of two numbers:
Enter two numbers:10 20
The sum is : 30

C Library Functions

 Library functions in C language are inbuilt functions which are grouped together and placed in a common place
called library.
 Each library function in C performs specific operation.
 We can make use of these library functions to get the pre-defined output instead of writing our own code to get
those outputs.
 These library functions are created by the persons who designed and created C compilers.
 All C standard library functions are declared in many header files which are saved as file_name.h.
 Actually, function declaration, definition for macros are given in all header files.
 We are including these header files in our C program using “#include<file_name.h>” command to make use of
the functions those are declared in the header files.
 When we include header files in our C program using “#include<filename.h>” command, all C code of the header
files are included in C program. Then, this C program is compiled by compiler and executed.

LIST OF MOST USED HEADER FILES IN C PROGRAMMING LANGUAGE:

 Check the below table to know all the C library functions and header files in which they are declared.
 Click on the each header file name below to know the list of inbuilt functions declared inside them.

Header file Description

This is standard input/output header file in which Input/Output


stdio.h
functions are declared
conio.h This is console input/output header file

string.h All string related functions are defined in this header file

stdlib.h This header file contains general functions used in C programs

math.h All maths related functions are defined in this header file

time.h This header file contains time and clock related functions

ctype.h All character handling functions are defined in this header file

stdarg.h Variable argument functions are declared in this header file

signal.h Signal handling functions are declared in this file


setjmp.h This file contains all jump functions
locale.h This file contains locale functions
errno.h Error handling functions are given in this file

assert.h This contains diagnostics functions

HOW TO CALL C FUNCTIONS IN A PROGRAM?


There are two ways that a C function can be called from a program. They are,

 Call by value
 Call by reference

1. CALL BY VALUE:

 In call by value method, the value of the variable is passed to the function as parameter.
 The value of the actual parameter can not be modified by formal parameter.
 Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.

Note:

Actual parameter – This is the argument which is used in function call.

Formal parameter – This is the argument which is used in function definition

EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):

 In this program, the values of the variables “m” and “n” are passed to the function “swap”.
 These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);

int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \n and n = %d", m, n);
swap(m, n);
}

void swap(int a, int b)


{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
OUTPUT:
values before swap m = 22 and n = 44
values after swap m = 44 and n = 22

2. CALL BY REFERENCE:
 In call by reference method, the address of the variable is passed to the function as parameter.
 The value of the actual parameter can be modified by formal parameter.
 Same memory is used for both actual and formal parameters since only address is used by both parameters.

EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):


 In this program, the address of the variables “m” and “n” are passed to the function “swap”.
 These values are not copied to formal parameters “a” and “b” in swap function.
 Because, they are just holding the address of those variables.
 This address is used to access and change the values of the variables.

#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);

int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}

void swap(int *a, int *b)


{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \n and b = %d", *a, *b);
}
OUTPUT:
values before swap m = 22 and n = 44
values after swap a = 44 and b = 22
Storage Class
A storage class represents the visibility and a location of a variable. It tells from what part of code we can access a
variable. A storage class in C is used to describe the following things:

 The variable scope.


 The location where the variable will be stored.
 The initialized value of a variable.
 A lifetime of a variable.

Thus a storage class is used to represent the information about a variable.

NOTE: A variable is not only associated with a data type, its value but also a storage class.

There are total four types of standard storage classes.

Storage class Purpose

auto It is a default storage class.

extern It is a global variable.

static It is a local variable which is capable of returning a value


even when control is transferred to the function call.

register It is a variable which is stored inside a Register.

1. EXAMPLE PROGRAM FOR AUTO VARIABLE IN C:

The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto
variables by default.

#include<stdio.h>
void increment(void);
void main()
{
increment();
increment();
increment();
increment();
}

void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
}
Output
0000

2. EXAMPLE PROGRAM FOR STATIC VARIABLE IN C:

Static variables retain the value of the variable between different function calls.
 The variables defined as static specifier can hold their value between the multiple function calls.
 Static local variables are visible only to the function or the block in which they are defined.
 A same static variable can be declared many times but can be assigned at only one time.
 Default initial value of the static integral variable is 0 otherwise null.

//C static example


#include<stdio.h>
void increment();
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment()
{
static int i = 10 ;
printf ( "%d ", i ) ;
i++;
}
Output

10 11 12 13

3. EXAMPLE PROGRAM FOR EXTERN VARIABLE IN C:

The scope of this extern variable is throughout the main program. It is equivalent to global variable. Definition for
extern variable might be anywhere in the C program.

#include<stdio.h>
int x = 10 ;
int main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;

Output
The value of x is 10
The value of y is 50
4. EXAMPLE PROGRAM FOR REGISTER VARIABLE IN C:

 Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in
main CPU memory.
 Register variables will be accessed very faster than the normal variables since they are stored in register
memory rather than main memory.
 But, only limited variables can be used as register since register size is very low.

#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
return 0;
}

Output
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

Recursion in C

Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem.
Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion
involves several numbers of recursive calls.

#include <stdio.h>
int factorial(int);
int main()
{
int i = 5;
printf("Factorial of the number %d is %d\n", i, factorial(i));
return 0;
}

int factorial(int i)
{
if(i < 2)
{
return 1;
}
return i * factorial(i - 1);
}
Output
Factorial of the number 5 is 120

C PREPROCESSOR DIRECTIVES:

 Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This
process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.

Preprocessor Syntax/Description

Syntax: #define
Macro
This macro defines constant value and can be any of the basic data types.

Syntax: #include <file_name>


Header file inclusion
The source code of the file “file_name” is included in the main program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Conditional
Set of commands are included or excluded in source program before compilation with respect
compilation
to the condition.

Syntax: #undef, #pragma


Other directives #undef is used to undefine a defined macro variable. #Pragma is used to call a function before
and after main function in a C program.

A program in C language involves into different processes. Below diagram will help you to understand all the processes
that a C program comes across.
KEY POINTS TO REMEMBER:

1. Source program is converted into executable code through different processes like precompilation, compilation,
assembling and linking.
2. Local variables uses stack memory.
3. Dynamic memory allocation functions use the heap memory.

EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C LANGUAGE:

 #define – This macro defines constant value and can be any of the basic data types.
 #include <file_name> – The source code of the file “file_name” is included in the main C program where
“#include <file_name>” is mentioned.

#include <stdio.h>

#define height 100 (Macro name-height macro body-100)


#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char 'K'

void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

Output

value of height : 100


value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : K

EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION DIRECTIVES:

A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:

 “#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause statements are
included in source file.
 Otherwise, “else” clause statements are included in source file for compilation and execution.

#include <stdio.h>
#define RAJA 100

int main()
{
#ifdef RAJA
printf("RAJA is defined. So, this line will be added in this C file\n");
#else
printf("RAJA is not defined\n");
#endif
return 0;
}
Output
RAJA is defined. So, this line will be added in this C file

EXAMPLE PROGRAM FOR PRAGMA IN C LANGUAGE:

Pragma is used to call a function before and after main function in a C program.

#include <stdio.h>

void function1( );
void function2( );

#pragma startup function1


#pragma exit function2

int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}

void function1( )
{
printf("\nFunction1 is called before main function call");
}

void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"

C Variable length argument


 Variable length arguments is an advanced concept in C language offered by c99 standard. In c89 standard, fixed
arguments only can be passed to the functions.

 When a function gets number of arguments that changes at run time, we can go for variable length arguments.

 It is denoted as … (3 dots)

 stdarg.h header file should be included to make use of variable length argument functions.
#include <stdio.h>
#include <stdarg.h>

int add(int num,...);

int main()
{
printf("The value from first function call = %d\n", add(2,2,3));
printf("The value from second function call= %d \n", add(4,2,3,4,5));

return 0;
}

int add(int num,...)


{
va_list valist;
int sum = 0;
int i;

va_start(valist, num);
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
va_end(valist);
return sum;
}
/*Note - In function add(2,2,3), first 2 is total number of arguments 2,3 are variable length arguments
In function add(4,2,3,4,5), 4 is total number of arguments 2,3,4,5 are variable length arguments
*/

Output

The value from first function call = 5


The value from second function call= 14
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 ->[Link]
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/> [Link] sample.c
->Generate [Link] file
Cmd/> [Link] 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