MODULE-4
ARRAYS AND
ARRAYS
An array is defined as the collection of
similar type of data items stored at
contiguous memory locations.
Arrays are the derived data type in C
programming language which can store
the primitive type of data such as int,
char, double, float, etc.
Properties of Array
Each element of an array is of same data
type and carries the same size, i.e., int =
4 bytes.
Elements of the array are stored at
contiguous memory locations where the
first element is stored at the smallest
memory location.
Elements of the array can be randomly
accessed since we can calculate the
address of each element of the array
with the given base address and the size
Advantage of C Array
1)Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can
retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we
need a few lines of code only.
4) Random Access: We can access any element
randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of
declaration of the array, we can't exceed the limit. So, it
doesn't grow the size dynamically like LinkedList which
we will learn later.
Declaration of Array
We can declare an array in the c
language in the following way.
data_type array_name[array_size];
Example to declare the array:
int marks[5];
Here, int is the data_type, marks are
the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is
by using the index of each element. We
can initialize each element of the array by
using the index.
Example:
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
C array example
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
OUTPUT
80
60
70
85
75
Array: Declaration with Initialization
We can initialize the c array at the time
of declaration.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to
define the size. So it may also be written
as the following code.
int marks[]={20,30,40,50,60};
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and
initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output
20
30
40
50
60
One-Dimensional Array
A list of items can be given one variable
index is called single subscripted
variable or a one-dimensional array.
The subscript value starts from 0. If we
want 5 elements the declaration will be
int number[5];
The elements will be number[0],
number[1], number[2], number[3],
number[4]
There will not be number[5].
Declaration of One -
Dimensional Arrays
Type variable – name [sizes];
Type – data type of all elements Ex: int, float
etc.,
Variable – name – is an identifier
Size – is the maximum no of elements that
can be stored.
Ex:- float avg[50]
This array is of type float. Its name is avg.
and it can contains 50 elements only. The
range starting from 0 – 49 elements.
Initialization One - Dimensional
Arrays
An array can be initialized in two ways,
which are as follows −
Compile time initialization
Runtime initialization
Example
Compile time initialization −
#include<stdio.h>
int main ( ){
int a[5] = {10,20,30,40,50};
int i;
printf ("elements of the array are");
for ( i=0; i<5; i++)
printf ("%d", a[i]);
}
Output:
Elements of the array are
10 20 30 40 50
Runtime initialization −
#include<stdio.h>
main ( ){
int a[5],i;
printf ("enter 5 elements");
for ( i=0; i<5; i++)
scanf("%d", &a[i]);
printf("elements of the array are");
for (i=0; i<5; i++)
printf("%d", a[i]);
}
OUTPUT:
enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50
program for one dimensional array
#include <stdio.h>
int main(void){
int a[4];
int b[4] = {1};
int c[4] = {1,2,3,4};
int i; //for loop counter
//printing all elements of all arrays
printf("\nArray a:\n");
for( i=0; i<4; i++ )
printf("arr[%d]: %d\n",i,a[i]);
printf("\nArray b:\n");
for( i=0; i<4; i++)
printf("arr[%d]: %d\n",i,b[i]);
printf("\nArray c:\n");
for( i=0; i<4; i++ )
printf("arr[%d]: %d\n",i, c[i]);
return 0;
Output
Array a:
arr[0]: 0
arr[1]: 0
arr[2]: 0
arr[3]: 0
Array b:
arr[0]: 1
arr[1]: 0
arr[2]: 0
arr[3]: 0
Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4
Multi-dimensional Arrays in C
C programming language allows
multidimensional arrays. Here is the
general form of multidimensional array
declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration
creates a three dimensional integer array
−
int threedim[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional
array is the two-dimensional array. A
two-dimensional array is, in essence, a
list of one-dimensional arrays. To declare
a two-dimensional integer array of size
[x][y], you would write something as
follows
type arrayName [ x ][ y ];
Where type can be any valid C data
type and arrayName will be a valid C
identifier.
A two-dimensional array can be
considered as a table which will have x
number of rows and y number of
columns.
A two-dimensional array a, which
contains three rows and four columns
can be shown as follows −
Thus, every element in the array a is
identified by an element name of the
form a[ i ][ J ], where 'a' is the name of
the array, and 'i' and ‘J' are the
subscripts that uniquely identify each
element in 'a'.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by
specifying bracketed values for each row. Following
is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The following initialization is equivalent to the previous example
−
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array
Elements
An element in a two-dimensional array is
accessed by using the subscripts, i.e.,
row index and column index of the array.
For example −
int val = a[2][3];
PROGRAM
#include <stdio.h>
int main () {
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ ) {
for ( J = 0; J < 2; J++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
OUTPUT:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
Passing Arrays to Function
In C, there are various general problems which requires passing
more than one variable of the same type to a function.
For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed
as the actual parameters from the main function.
Here, instead of declaring 10 different numbers and then passing
into the function, we can declare and initialize an array and pass
that into the function. This will resolve all the complexity since the
function will now work for any number of values.
As we know that the array_name contains the address of the first
element. Here, we must notice that we need to pass only the name
of the array in the function which is intended to accept an array.
The array defined as the formal parameter will automatically refer
to the array specified by the array name defined as an actual
parameter.
syntax to pass an array to the function:
functionname(arrayname);//passing array
There are 3 ways to declare the function
which is intended to receive an array as an
argument.
First way:
return_type function(type arrayname[])
Declaring blank subscript notation[] is the widely
used technique.
Second way:
return_type function(type arrayname[SIZE]
)
Optionally, we can define size in subscript
notation [].
Third way:
return_type function(type *arrayname)
C language passing an array to function
example
#include<stdio.h>
int minarray(int arr[],int size){
int min=arr[0];
int i=0;
for(i=1;i<size;i++){
if(min>arr[i]){
min=arr[i]; } }//end of for
return min;
}//end of function
int main(){
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array
min=minarray(numbers,6);//passing array with size
printf("minimum number is %d \n",min);
return 0;
}
output
minimum number is 3
STRINGS: ONE-DIMENSIONAL
CHARACTER ARRAYS
Strings in C are represented by arrays of
characters. The end of the string is marked with a
special character, the null character, which is a
character all of whose bits are zero, i.e., a NUL
(not a NULL).
(The null character has no relation except in
name to the null pointer. In the ASCII character
set, the null character is named NUL.)
The null or string-terminating character is
represented by another character escape
sequence, \0.
Although C does not have a string data type, it
allows string constants.
Declaration of a String
Strings can be declared like one-
dimensional arrays. For
Example:
char str[30];
String Initialization
Character arrays or strings allow a
shorthand initialization,
for example,
char str[9] = “I like C”;
which is the same as
char str[9] = {‘I’,‘ ’,‘l’,‘i’,‘k’,‘e’,‘
’,‘C’,‘\0’};
Whenever a string, enclosed in double
quotes, is written,C automatically
creates an array of characters containing
that string, terminated by the \0
character. C language allows the
alternative notation
char msg[] = “Hello”;
Printing Strings
The conversion type ‘s’ may be used for output of
strings using printf().
Width and precision specifications may be used with
the %s conversion specifier.
The width specifies the minimum output field width; if
the string is shorter, then space padding is generated.
The precision specifies the maximum number of
characters to display.
If the string is too long, it is truncated. A negative
width implies left justification of short strings rather
than the default right justification. For example,
printf(“%7.3s”,name)
This specifies that only the first three
characters have to be printed in a total
field width of seven characters and right
justified in the allocated width by
default.
We can include a minus sign to make it
left justified (%-7.3). The following points
should be noted.
When the field width is less than the length
of the string, the entire string is printed.
The integer value on the right side of the
decimal point specifies the number of
characters to be printed.
When the number of characters to be printed
is specified as zero, nothing is printed.
The minus sign in the specification causes
the string to be printed as left justified.
#include <stdio.h> OUTPUT:
int main()
{
char s[]=“Hello, World”;
printf(“>>%s<<\n”,s);
printf(“>>%20s<<\n”,s);
printf(“>>%-20s<<\n”,s);
printf(“>>%.4s<<\n”,s);
printf(“>>%-20.4s<<\n”,s);
printf(“>>%20.4s<<\n”,s);
return 0;
}
The >> and << symbols are included in
this program so that the limits of the
output fields are clearly visible in the
output.
String Input
Using %s control string with scanf():
Strings may be read by using the %s conversion with the
function scanf() but there are some irksome restrictions.
The first is that scanf() only recognizes a sequence of
characters delimited by white space characters as an
external string.
The second is that it is the programmer’s responsibility to
ensure that there is enough space to receive and store the
incoming string along with the terminating null which is
automatically generated and stored by scanf() as part of
the %s conversion.
The associated parameter in the value list must be the
address of the first location in an area of memory set aside
to store the incoming string.
PROGRAM
int main()
{
char str[50];
printf(“Enter a string”);
scanf(“%s”,str);
printf(“The string was :%s\n”,str);
return 0;
}
OUTPUT:
Enter a string manas
The string was :manas
Using scanset
The scanset is basically a specifier
supported by scanf family functions.
It is represented by %[]. Inside scanset
we can specify only one character or a
set of characters (Case Sensitive).
When the scanset is processed, the
scanf() can process only those
characters which are mentioned in the
scanset.
PROGRAM
#include<stdio.h>
int main()
{
char str[50];
printf("Enter something: ");
scanf("%[A-Z]s", str);
printf("Given String: %s", str);
}
OUTPUT:
Enter something: HElloWorld
Given String: HE
It ignores the characters which are
written in lowercase letters. The ‘W’ is
also ignored because there are some
lower case letters before it.
Now, if the scanset has ‘^’ in its first
position, the specifier will stop reading
after first occurrence of that character.
PROGRAM
#include<stdio.h>
int main()
{
char str[50];
printf("Enter something: ");
scanf("%[^r]s", str);
printf("Given String: %s", str);
}
OUTPUT:
Enter something: HelloWorld
Given String: HelloWo
Here the scanf() ignores the characters
after getting the letter ‘r’.
Using this feature, we can solve the
problem that a scanf does not take
strings with spaces.
If we put %[^\n], then it will take all of
the characters until it gets a new line
character.
PROGRAM
#include<stdio.h>
int main()
{
char str[50];
printf("Enter something: ");
scanf("%[^\n]s", str);
printf("Given String: %s", str);
}
OUTPUT:
Enter something: Hello World
Given String: Hello World
Using gets()
The gets() function enables the user to
enter some characters followed by the
enter key.
All the characters entered by the user get
stored in a character array.
The null character is added to the array to
make it a string.
The gets() allows the user to enter the
space-separated strings.
It returns the string entered by the user.
PROGRAM
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
OUTPUT:
Enter the string?Hello World
You entered Hello World
Character Manipulation in the
String
In working with a string, one important
point to be remembered is that it must
be terminated with NUL (\0).
#include<stdio.h>
#include<string.h>
int main()
{
char a[80],t[80];
int i,j;
printf("\n enter the text\n");
gets(a);
for(i=0,j=0;a[i]!='\0';++i)
if(a[i]!= ' ')
t[j++]=a[i];
t[j]='\0';
printf("\n The text without blank spaces\n");puts(t);
return 0;
}
OUTPUT:
enter the text
Hello World
The text without blank spaces
HelloWorld
Character functions in <ctype.h> where
c is the character argument
String Manipulation
C has the weakest character string capability of any
general-purpose programming language. Strictly
speaking, there are no character strings in C, just
arrays of single characters that are really small
integers. If s1 and s2 are such ‘strings’ a program
cannot
assign one to the other: s1 = s2;
compare them for collating sequence: s1 < s2
concatenate them to form a single longer string: s1 + s2
return a string as the result of a function
The string header, string.h, provides many functions
useful for manipulating strings or character arrays.
String manipulation functions
available in string.h
#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
printf("Enter a string to reverse\n");
gets(s);
strrev(s);
printf("Reverse of the string: %s\n", s);
return 0;
}
OUTPUT
Copying a string into
another
#include<stdio.h>
#include<string.h>
main()
{
char source[] = "C Program";
char destination[50];
strcpy(destination, source);
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
return 0;
}
OUTPUT
Source string: C Program
Destination string: C Program
ARRAYS OF STRINGS:
TWO-DIMENSIONAL CHARACTER ARRAY
A two-dimensional array of strings can
be declared as follows:
<data_type> <string_array_name>[<row_size>][<columns_size>];
Consider the following example on declaration of a two-dimensional
array of strings.
char s[5][30];
Initialization
Two-dimensional string arrays can be
initialized as shown
char s[5][10]
={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};
which is equivalent to
Here every row is a string. That is, s[i] is
a string. Note that the following
declarations are invalid.
char s[5][]
={“Cow”,“Goat”,“Ram”,”Dog”,“Cat”};
char s[][]
={“Cow”,“Goat”,“Ram”,“Dog”,“Cat”};
Manipulating String
Arrays
The following codes show how arrays of strings may be
manipulated. This program checks whether a number is odd
or even without using any control statement.
#include <stdio.h>
int main()
{
char s[2][5]={“EVEN”,“ODD”};
int n;
printf(“\n enter the number:”);
scanf(“%d”,&n);
printf(“\n The number is %s”,s[n%2]);
return 0;
}
Output:
enter the number:25
The number is ODD
POINTERS
Pointers:Fundamentals
The pointer in C language is a variable which stores
the address of another variable.
This variable can be of type int, char, array, function,
or any other pointer.
The size of the pointer depends on the architecture.
However, in 32-bit architecture the size of a pointer is
2 byte.
Example to define a pointer which stores the address of
an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of
the variable n of type integer.
Suppose v is a variable that represents some
particular data item.
The compiler will automatically assign memory
cells for this data item.
The data item can then be accessed if we know
the location (i.e., the address)of the first
memory cell.
* The address of v ’s memory location can be
determined by the expression &v, where & is a
unary operator, called the address operator,
that evaluates the address of its operand.
Now let us assign the address of v to
another variable, pv. Thus,
pv = &v
This new variable is called a pointer to
v, since it “points” to the location where
v is stored in memory.
Remember, however, that pv represents
v’s address, not its value. Thus, pv is
referred to as a pointer variable.
The data item represented by v (i.e., the data
item stored in v’s memory cells) can be accessed
by the expression *pv, where * is a unary
operator, called the indirection operator, that
operates only on a pointer variable.
Therefore, *pv and v both represent the same
data item (i.e., the contents of the same memory
cells).
Furthermore, if we write pv = &v and u = *pv,
then u and v will both represent the same value;
ie., the value of v will indirectly be assigned to u.
EXAMPLE
#include<stdio.h>
main( )
int u=3;
int v;
int *pu; /* pointer t o an integer */
int *pv; /* pointer t o an integer */
pu=&u; / * assign address of u to pu */
v= *pu; / * assign value of u t o v */
pv=&v; /* assign address of v t o pv */
printf("\nu=%d &u=%x pu=%x *pu=%d',u,&u,pu, *pu);
printf("\n\nv=%d &v=%x pv=%x *pv=%d", v, &v, pv, *pv);
}
u=
&u=
pu=
*pu=
v=
&v=
pv=
*pv=
Execution of this program results in the
following output.
u=3 &u=F8E pu=F8E *pu=3
v=3 &v=F8C pv=F8C *pv=3
Pointer Declarations
The pointer in c language can be
declared using * (asterisk symbol). It is
also known as indirection pointer used to
dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Example
pointer variable stores the address of
number variable, i.e., fff4. The value of
number variable is 50. But the address
of pointer variable p is aaa3.
By the help of * (indirection operator),
we can print the value of pointer variable
p.
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \
n",p); // p contains the address of the number therefore printing p gives t
he address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to
dereference a pointer therefore if we print *p, we will get the value stored
at the address contained by p.
return 0;
}
OUTPUT
Address of number variable is fff4
Value of p variable is 50
Operations on pointers
We can perform arithmetic operations on the
pointers like addition, subtraction, etc.
C Pointer Addition:
We can add a value to the pointer variable. The
formula of adding value to pointer is given below:
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.
#include<stdio.h>
int main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u\n",p);
p=p+3;
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.
#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
Passing Pointers to a
Function
C programming allows passing a pointer
to a function. To do so, simply declare
the function parameter as a pointer
type.
Following is a simple example where we
pass an unsigned long pointer to a
function and change the value inside the
function which reflects back in the
calling function −
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Pointers and Arrays
Pointers and arrays are inseparably
related, but they are not synonymous.
Differences between pointers and arrays
One-dimensional Arrays and Pointers
One-dimensional Arrays and Pointers
An array is a non-empty set of sequentially
indexed elements having the same type of
data.
Each element of an array has a unique
identifying index number.
Changes made to one element of an array does
not affect the other elements. An array
occupies a contiguous block of memory.
The array a is laid out in memory as a
contiguous block, as shown.
Elements of array are stored in the
successive increasing locations of memory.
For example, if the array starts at memory
location 2147478270 (considering a 32-bit
machine), then with the assumed size of an
integer as four bytes, the first element is
stored at location 2147478270, the second
element at location 2147478274, and so
on.
Array notation is a form of pointer
notation. The name of an array is the
beginning address of the array, called the
base address of the array. That is, the base
address of an array is the address of the
zeroth element of the array.
The array name is referred to as an
address constant.
Mentioning the name of the array fetches
its base address.
PROGRAM
#include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array[0]);
return 0;
}
OUTPUT:
2147478270 2147478270
Arrays of Pointers
we can declare an array of int, float or char etc,
we can also declare an array of pointers, here is
the syntax to do the same.
Syntax: datatype *array_name[size];
Let's take an example:
int *arrop[5];
Here arrop is an array of 5 integer pointers. It
means that this array can hold the address
of 5 integer variables. In other words, you can
assign 5 pointer variables of type pointer to int to
the elements of this array.
#include<stdio.h>
#define SIZE 10
int main()
{
int *arrop[3];
int a = 10, b = 20, c = 50, i;
arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c;
for(i = 0; i < 3; i++)
{
printf("Address = %d\t Value = %d\n", arrop[i], *arrop[i]);
}
return 0;
}
Output:
Address = 1086509664 Value = 10
Address = 1086509668 Value = 20
Address = 1086509672 Value = 50
Pointer to Pointer
A pointer to a pointer is a form of
multiple indirection, or a chain of
pointers. Normally, a pointer contains
the address of a variable.
When we define a pointer to a pointer,
the first pointer contains the address of
the second pointer, which points to the
location that contains the actual value as
shown below.
A variable that is a pointer to a pointer must
be declared as such. This is done by placing
an additional asterisk in front of its name.
For example, the following declaration
declares a pointer to a pointer of type int −
int **var;
When a target value is indirectly pointed to
by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied
twice, as is shown below in the example −
#include<stdio.h>
int main(){
int a = 10;
int *ptr = &a; //ptr references a int
**dptr = &ptr; //dptr references ptr
printf("Address of a = %p\n",&a);
printf("ptr is pointing to the address = %p\n",ptr);
printf("dptr is pointing to the address = %p\n",dptr);
printf("Value of a = %d\n",a);
printf("*ptr = %d\n",*ptr);
printf("**dptr = %d\n",**dptr);
return 0;
}
OUTPUT
Address of a = 0x7ffda86fc274
ptr is pointing to the address =
0x7ffda86fc274
dptr is pointing to the address =
0x7ffda86fc278
Value of a = 10
*ptr = 10
**dptr = 10
Pointer to Functions
As we know that we can create a pointer of any data type such
as int, char, float, we can also create a pointer pointing to a
function. The code of a function always resides in memory,
which means that the function has some address. We can get
the address of memory by using the function pointer.
#include <stdio.h>
int main()
{
printf("Address of main() function is %p",main);
return 0;
}
OUTPUT:
Address of main() function is 0x556f6c10a149
Declaration of a function pointer
Syntax of function pointer
return type (*ptr_name)(type1, type2…);
For example:
int (*ip) (int);
In the above declaration, *ip is a pointer
that points to a function which returns an
int value and accepts an integer value as
an argument.
Calling a function through a function pointer
float func(int , int); // Declaration of a fun
ction.
Calling an above function using a usual
way is given below:
result = func(a , b); // Calling a function using
usual ways.
Calling a function using a function pointer is given
below:
result = (*fp)
( a , b); // Calling a function using function pointer.
#include<stdio.h>
int (*add)(int,int);
int main()
{
int a,b;
int result;
printf("Enter the values of a and b:");
scanf("%d %d",&a,&b);
result=(*add)(a,b);
printf("Value after addition is :%d",result);
return 0;
}
int add(int x,int y)
{
int c=x+y;
return c;
}
OUTPUT
Enter the values of a and b :4
55
Value after addition is :59
Command line arguments
The arguments passed from command line are
called command line arguments. These arguments
are handled by main() function.
To support command line argument, you need to
change the structure of main() function as given
below.
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It
counts the file name as the first argument.
The argv[] contains the total number of
arguments. The first argument is the file name
always.
#include <stdio.h>
void main(int argc, char *argv[])
{
int i;printf("\nNumber of arguments are: %d\n", argc);
for(i=0;i<argc;i++)
{
printf("\n Argument [%d] is : %s", i,argv[i]);
}
} OUTPUT:
Argument [0] is : ./a.out
Argument [1] is : Hello
Argument [2] is : How
Argument [3] is : are
Argument [4] is : you
Dynamic Memory
Management
The concept of dynamic memory
allocation in c language enables the C
programmer to allocate memory at
runtime. Dynamic memory allocation in c
language is possible by 2 functions of
stdlib.h header file.
malloc()
calloc()
malloc() allocates single block of
requested memory.
calloc() allocates multiple block of
requested memory.
malloc() function in C
The malloc() function allocates single
block of requested memory.
It doesn't initialize memory at execution
time, so it has garbage value initially.
It returns NULL if memory is not
sufficient.
The syntax of malloc() function is given
below:
ptr=(cast-type*)malloc(byte-size) ;
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr;
printf("Enter number of elements:");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
printf("Sorry! unable to allocate memory");else
{
printf("Entered elements of array:");
for(i=0;i<n;++i)
scanf("%d",ptr+i);
printf("Entered elements are:");
for(i=0;i<n;++i)
printf("%d ",*(ptr+i));
}
free(ptr);
return 0;
}
OUTPUT
Enter number of elements:3
Entered elements of array:5
6
8
Entered elements are:5 6 8
calloc() function in C
The calloc() function allocates multiple
block of requested memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not
sufficient.
The syntax of calloc() function is given
below:
ptr=(cast-type*)calloc(number, byte-
size) ;
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //
memory allocated using calloc
if(ptr==NULL)
printf("Sorry! unable to allocate memory");else
{
printf("Entered elements of array:");
for(i=0;i<n;++i)
scanf("%d",ptr+i);
printf("Entered elements are:");
for(i=0;i<n;++i)
printf("%d ",*(ptr+i));
}
free(ptr);
return 0;
}
OUTPUT:
Enter number of elements:3
Entered elements of array:5
6
8
Entered elements are:5 6 8