Unit-II
Arrays, Strings, Structures and Pointers
ARRAYS
WHY DO WE NEED ARRAYS?
Say we have a problem in our hand to store marks scored by 50 students in C language subject. To
store 50 marks we have to declare 50 variables of integer data type as shown below:
int marks_1, marks_2, marks_3, marks_4… ...........................marks_50;
Now suppose we have to store values into these variables then 50 scanf statements or initializing 50
values has to be done as shown:
scanf(“%d”, marks_1);
scanf(“%d”, marks_2);
scanf(“%d”, marks_3);
………………..scanf(“%d”, &marks_50);
OR
marks_1= 5;
marks_2=23;
marks_3=20;
………….. so on marks_50=21;
marks_1 25 marks_2 23 marks_3 20
marks_4 15 So on………… marks_50 21
This style of programming is fine for a small set of values. But if we have to store 1000 or 10000
values declaring so many variables is a cumbersome process. Alternative solution is Arrays!
DEFINITION OF ARRAYS
The array is a fixed-size sequenced collection of elements of same data type.
The array is a collection of homogeneous elements of same data type.
Array groups the data items of similar types sharing the common name.
Arrays are called as subscripted variables because; it is accessed using
subscripts/indexes.
Ex: 1. List of employees in an organization.
2. List of products and their cost sold by a store.
3. Test scores of a class of students.
Heremarks[0]=10, marks[1]=20, marks[2]=30 and marks[3]=40. This
subscript/index notation is borrowed from Mathematics where we have the practice of
writing: marks4, marks3, marks2 and so on.
In C the array index starts with 0.
TYPES OF ARRAYS
I. One dimensional arrays/Single-Subscripted Variable
II. Two dimensional arrays/Double-Subscripted Variable
III. Multidimensional arrays
I. One-Dimensional Arrays: A list of items can be given one variable name using
only one subscript and such a variable is called a single subscripted variable or one
dimensional array.
Ex: int marks[4];
Here marks is the name of the array which is capable of storing 4 integer values.
The first value will be stored in marks[0], the second value will be stored in marks[1]
and so on and the last value will be in marks[3].
Declaration of One-Dimensional Array: Here is general syntax for array declaration
along with examples.
Syntax: data_type array_name[size];
Examples: int marks[4];
float temperature[5];
Note: Declaration and definition specify the data type of
array, its name and size.
Initialization of One-Dimensional Array: After array is declared, next is storing
values in to an array is called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization
1. Compile time initialization: If we assign values to the array during declaration
it is called compile time initialization. Following are the different methods of compile
time initialization.
a) Initialization with size
b) Initialization without size
c) Partial initialization
d) Initializing all values zero
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[5]={29.5, 30.7, 35.6, 45.7, 19.5};
b) Initialization without size: We needn’t have to specify the size of array provided
we are initializing the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
c) Partial initialization: If we not specify the all the elements in the array, the
unspecified elements will be initialized to zero.
Example: int marks[5]={10,12,20};
Here, marks[3] and marks[4] will be initialized to zero.
d) Initializing all the elements zero: If we want to store zero to all the elements in
the array we can do.
Examples: int marks[4]={0};
float temperature[5]={0};
2. Run time initialization: Run time initialization is storing values in an array
when program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example:
printf(“Enter the marks”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
Note: Every iteration of for loop will help us to fill values into marks array (i.e.
marks[0]=95, marks[1]=35, marks[2]=67, marks[3]=87)
Accessing the array elements: Accessing the array element is done using a loop
statement in combination with printf statements or any other processing statements.
Example of accessing the array elements and calculating total marks is given below:
Example: void main( )
{
int total=0, marks[4]={35,44,55,67};
for(i=0; i<4; i++)
total=total+marks[i]; /* calculating total marks*/
printf(“Total marks=%d”,total);
}
Output: Total marks=201
II. Two-Dimensional Arrays: A list of items can be given one variable name using
two subscripts and such a variable is called a single subscripted variable or one
dimensional array
It consists of both rows and columns. Ex: Matrix.
Declaration of Two-Dimensional Array: Here is general syntax for array declaration
along with examples.
Syntax: data_type array_name[row_size][column_size];
Examples: int marks[4][4];
float city_temper[3][3];
Note: Declaration and definition specify the data type of
array, its name and size.
Initialization of Two-Dimensional Array: After array is declared, next is storing
values in to an array is called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization
1. Compile time initialization: If we assign values to the array during declaration
it is called compile time initialization. Following are the different methods of compile
time initialization.
Syntax: data_type array_name[size]={list of values};
Examples: int marks[3][4]={ 1,2,3, 4, 5, 6, 7,8,9,10,11,12};
After initialization the arrays appear as follows:
1 2 3 4
marks
5 6 7 8
2. Run time initialization: Run time initialization is storing values in an array
when program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example: printf(“Enter the marks”);
for(i=0; i<3; i++)
for(j=0;j<4;j++)
{
scanf(“ %d”, &marks[i][j]);
}
More Examples: Other way of initialization:
int a[ ][3]= { 0, 1, 2, 3,4,5,6,7,8};
int b[ ][4] ={1,2,3,4,5,6,7,8,9,10,11,12};
012 1234
a b
345 5678
67 8 9 10 11 12
Example for Invalid initialization
int A[3][ ]={1,2,3};
Note: Never have column size undeclared in two dimension array.
III. Multi Dimensional Arrays: Multidimensional arrays can have three, four or
more dimensions.
A three-dimension array is an array of two dimensional arrays. It has row, column
and depth associated with it.
Declaring multidimensional arrays
int table[3][4][2];
Here are two examples illustrating three-dimensional array declaration and
initialization
A[3][4][2]={
{
{ 1,2},
4 rows &
{3,4},
{5,6}, 2 columns
{7,8},
},
{ 3 depth
{ 8,9},
{10,11},
{12,13},
{14,15},
},
{
{ 8,9},
{10,11},
{12,13},
{14,15},
}
}
STRING CONCEPTS
Definition: String is a variable length data stored in a character array.
Example: “hello”, “India”
I. C- strings
In C a string is a data structure based on an array of char.
A string is a sequence of elements of the char data type.
There is no separate data-type called string in C language.
As strings are variable-size data we have to represent them using character
Arrays.
Example string is:
R A J E S H \0 Delimiter ‘\0’
indicates end of
0 1 2 3 4 5 6 string
Strings in C are classified into two types:
1. String literals
2. String variables
String literals are also known as string constants, is a sequence of characters enclosed
by double quotation marks is called string literals. A string literal is a constant its value
cannot be changed. Some examples are:
Examples: “New Delhi”, “I Love India” etc.
String variables are nothing but character array. Following syntax and examples
illustrates declaring string variables.
Example: char array_name[ ]= “raj”
How string is stored?
A string, even a literal one is very similar to an array of characters.
The only difference between array of char and string is that, a string must end
with null character (\0).
If you use a literal string in a program, it is stored in consecutive bytes in memory
and compiler places the null character at the end.
Declaring string variables: A string is declared like an array of characters.
Syntax: char string_name[size];
Ex: char name[21];
Size 21 means it can store up to 20 characters plus the null character. Entire storage
location name is divided in to 21 boxes called bytes, each of which holds one character.
Each character is element of data type char.
Initializing the string in the declaration
char first[10]={‘t’,’a’,’b’,’l’,’e’,’\0’};
char second[10]=”table”;
Difference between a single character string and a single character array is:
Single character array takes 1 byte whereas single character string occupies two bytes
as shown below:
A \0 Single character string
Printing and reading a string: Token oriented input/output function
Printing a string using printf: We can use printf function with %s format specifier to
print a string on to the monitor. The %s is used to display an array of characters that is
terminated by null character.
Example:
(1) char name[10]=”Andy”;
printf(“the name is %s\n”,name);
o/p: the name is Andy
(2) char name[ ]= “ MANGALORE”;
printf(“%s”, name);
printf (“%9.6s”, name);
printf(“%-10.3s”, name);
M A N G A L O R E %s prints entire string
%9.6s prints first 6 characters out of 9
M A N G A L
characters
Prints first 3 characters but in left
M A N justified manner because of (- ) sign
Reading a string using scanf( )
It uses string conversion specifier %s to accept a string data. Following example
illustrates it:
char name[20];
scanf(“%s”, name);
Note: while reading strings we needn’t specify address of operator (&) as the character
array itself is an address (i.e name itself is base address of array in the above example)
String manipulation function:
C library supports a large number of string handling functions that can be used to
carry out many of the string manipulations and are stored in header file “string.h”.
Following are the most commonly used string handling functions.
1. strcpy( ) copies one string over another
2. strlen( ) finds the length of a string
3. strcmp( ) compare two strings
4. strcat( ) concatenates two strings
5. strcpy( ) copies left most n characters of source to destination
6. strcmp( ) compares left most of n characters of source to destination.
1. strcpy( ): It is possible to assign a value to a string variable using strcpy( ). It
allows us to copy a string from one location to another. The string to be copied can be
literal or string variable. The general form of call to strcpy is
strcpy(dest,source);
Strcpy() function has two parameters. The first is the dest, a string variable whose value
is going to be changed. The second is the source the string literal or variable which is
going to be copied to the destination.
Ex: char first[14];
char last[14];
strcpy(first,”ravi kumar”);
strcpy(last,first);
After two calls to strcpy, first and last each has a value “Ravi kumar”
Strcpy does not check to see whether there is room for the resulting string at the
specified location. If there is no room, it copies characters on top of whatever variables
follow in memory. This may destroy the contents of other variables.
2. strlen():the string length function can be used to find the length of the string in
bytes. It takes the form
length=strlen(str);
The parameter to strlen, str is a string. The return value length is an integer
representing current length of str in bytes excluding the null character.
Ex: str=”SICET”
lenth=strlen(str); //5
str=’\0’
length=strlen(str); //0
3. strcmp( ): A strcmp() is used to compare two strings. It takes the two
strings as a parameter and returns an integer value based on the relationship
between two strings.
General form of call to strcmp()
result=strcmp(first,second);
result>0 if first> second
result=0 if first==second
result<0 if first<second
Ex: int res;
res=strcmp(“cat”,”car”); //res>0
res=strcmp(“pot”,”pot”);//res==0
res=strcmp(“big”,”little”); //res<0
4. strcat( ): often it is useful to concatenate or join two strings together. The
strcat function is used to join two strings together. The resulting string has only one
null character at the end.
General form of a call to strcat( )
strcat(first, second);
After the call, first contains all the characters from first, followed by the ones from
second up to and including the first null character in second.
Note: strcat stops copying when it finds a null character in the second string. If it
doesn’t find a null character, strcat continues copying bytes from memory until it finds
null character. The programmer must check to make sure that the resulting string fits in
the variable.
Ex: char dest[30]=”computer”;
char second[15]=” programming”;
strcat(dest,second); //computer programming
5. strncmp( ): The strncmp function compares up to specified number of
characters from the two string, starting at the address specified, and returns integer
representing the relationship between the compared string sections. It compares the
character by character until it finds a null character or characters that are different or
until it has compared number of characters.
General form of call to strncmp()
Result=(firstaddress, secondaddress, numchars);
Ex: char first[30]=”string”;
char second[10]=”stopper”;
int n;
if(strncmp(first,second,4)==0)
printf(“first four characters are alike\n”);
else if(strncmp(first,second,4)<0)
printf(“first four characters of first string are less\n”);
else
printf(“first four characters of first string are greater\n”);
6. strncpy( ): The strncpy function allows us to extract a substring from one
string and copy it to another location.
General form of call to strncpy
strncpy(dest, source, numchars);
The strncpy function takes three parameters. Here this statement copies the numchars
of the source string in to dest string. Since numchar does not include null character , we
have to place it explicitly in the source string.
Ex: char source[20]=”computer world”;
char dest[10];
strncpy(dest,source,3); //first three characters of source is copied into dest
dest[3]=’\0’; //we have to put null character at the end of dest string
printf(“%s”,dest); //com
Array of strings: Array of string is an array of one dimensional character array, which
consists of strings as its individual elements.
Declaration of array of strings: Char name[size1][size2];
Ex:
char days[7][10]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};
Structure
Structure is a collection of elements of different data type.”
We can store values of different types using a single name is STRUCTURE
DECLARATION:
We can declare a structure in two ways
1. Tagged structure
2. type defined structure
1. Tagged structure:
Syntax:
Struct tagname
{
datatype memeber1;
datatype memeber2;
---
};
Tagged structure begins with keyword “struct”.
The tag name is the name of the structure.
The variables declared be terminated with a semi colon “;”.
A structure will always be terminated with “;”.
Ex: struct student
{
char sno[10];
char sname[20];
int m1,m2,m3;
float avg;
};
2. typedef structures:
A structure declared using the keyword “typedef” is called type defined structure.
Syntax:
typedef struct
{
datatype member1;
datatype member2;
---
}tagname;
Ex: typedef struct
{
char sno[10];
char sname[20];
int m1,m2;
}student;
Declaring a structure variable:
After defining a structure, we have to declare a variable for the entire structure.
Once a variable is declared, then the memory will be allocated for the structure
members.
We can declare the structures outside and inside the main() function. If it is declared
inside main(), it will have local scope only, whereas if we declare outside main() it will
have global scope which allows us to use the structure in other functions also.
Syntax for Tagged structure
Struct typename var1,var2,. ;
Syntax for typedef structure:
Typename var1,var2,. ;
Ex:
struct student s; (tagged structure)
student s; (typedef structure)
Accessing structure members:
The structure members should be accessed only through a structure variable using a
“.”(dot) operator.
Syntax: [Link]
/*PROGRAM TO STORE AND READ THE DATA FROM STRUCTURE /
#include<stdio.h>
struct student
{
char id[10];
char name[15];
int m1;
float m2;
float tot;
};
void main()
{
struct student s;
clrscr();
printf("\nEnter student details\nid name marks1 marks2\n");
scanf("%s%s%d%f",[Link], [Link], &s.m1, &s.m2);
[Link] = s.m1 + s.m2;
printf("\n Hello %s! Your Total marks are: %f",[Link],[Link]);
getch();
}
O/P:
Enter student details
id name marks1 marks2
A123 RAVI 89 98.89
Hello RAVI! Your Total marks are: 187.889999
STRUCTURE INITIALIZATION:-
We can initialize structure variables just like a variable.
The structure members should not be initialized because; they are not variables, but
members of a structure.
Initialization must be done only to structure variables.
Ex 1:
struct student
{
int rno;
char name[20];
}s={1,”abc”};
In structure initialization if some values are missing, then those values will be initialized
to zero for numbers or null characters (‘\0’) for strings.
Ex 2:
struct
{
int a;
float b;
char name[20];
}s1={1,1.1},s2={1};
s1 initializes a to 1, b to 1.1 and name to ‘\0’.
s2 initializes a to 1, b to 0.0 and name to ‘\0’.
UNIONS:
Union is a collection of elements of different datatypes.
The difference between structures and unions will be in terms of storage.
Each member of a structure has its own memory location, whereas all the members of
the union share the same memory location.
Syntax:
union tagname
{
data type member1;
data type member2;
--
--
};
Ex:
union
{
int a;
float b;
char c;
};
The size of the above union is 4 bytes which is the size of the largest data type.
We can access only one member at a time because same memory is used by all the
members of a union.
/*PROGRAM TO ILLUSTRATE ABOUT UNION*/
#include<stdio.h>
union student
{
char name[15];
int m1;
float m2;
};
void main()
{
union student u;
clrscr();
strcpy([Link],"Raj");
printf("\nHello %s",[Link]);
u.m1=88;
printf("\nMarks1= %d",u.m1);
u.m2=96.57;
printf("\nMarks2= %f",u.m2);
}
O/P:
Hello Raj
Marks1= 88
Marks2= 96.570000
POINTERS
A pointer is a variable which stores the address of another variable.
A pointer is a derived data type in c.
Pointers contain memory addresses as their values.
Pointers can be used to access and manipulate data stored in the memory.
Pointers concept is built using the following 3 concepts:
pointer constant
pointer value
pointer variable
Every memory location has an address which is constant. It is called "pointer constant".
To access the memory address we have to use the "address of" operator (&).
The value thus obtained is called "pointer value".
We can store the address in another variable.
A variable which the stores the address of a pointer value is called as a "pointer variable".
& address of an operator to know the address of a variable.
* value at address operator is used to get the value of the variable there in the pointer.
DECLARATING A POINTER VARIABLE:
Syntax:
datatype *pointer variable;
The " * " (asterisk) tells the compiler that the variable is a pointer.
The datatype is the type of the value, whose address is to be stored.
Ex: float a=3.14; float *p=&a;
Hear float is not the datatype of the pointer variable p but is the datatype of
the variable a, whose address is stored in that pointer variable p.
INITIALIZING A POINTER:
Assigning address of a variable to a pointer is called "initialization".
To get the address, we have to use "&" symbol.
Ex: int a;
int *p;
//declaration//
p=&a; //initializion//
A pointer variable will be assigned null if the address is not assigned to it.
We can declare and initialize pointers as follows.
We can assign a simple character called 'NULL' to a pointer variable. p=
‘\0’ (or) p=NULL
We can assign "0" to a pointer variable.
p=0;
ACCESSING THE VALUE IN THE VARIABLE THROUGH THE POINTERS:
We can access the value of the variable there in the pointer by using *, which is called
"indirection operator" or "dereferencing operator" or “value at the address of”
operator.
/*PROGRAM TO ADD TWO NO.S USING POINTERS*/
#include<stdio.h>
Void main()
{
int a=10,b=20;
int *pa,*pb;
pa=&a, pb=&b;
clrscr();
printf("Sum=%d", *pa+*pb);
getch();
}
O/P: Sum=30;
ADVANTAGES OF POINTERS:
Pointers increase the speed of execution.
Pointers are more efficient in handling arrays.
Pointers allow C to support dynamic memory management.
Pointers reduce length and complexity of programs.
Pointers save storage space in memory.
Pointer to Structures:
Self Referential Structures:
Self Referential structures are those structures that have one or more pointers which point to the same
type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-
referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing, as by
default it contains garbage value.
Types of Self Referential Structures
1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links
Self Referential Structure with Single Link:
These structures can have only one self-pointer as their member. The following example will show us
how to connect the objects of a self-referential structure with the single link and access the corresponding
data members.
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Initialization
[Link] = NULL;
ob1.data1 = 10;
ob1.data2 = A;
struct node ob2; // Node2
// Initialization
[Link] = NULL;
ob2.data1 = 30;
ob2.data2 = B;
// Linking ob1 and ob2
[Link] = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", [Link]->data1);
printf("\n%d", [Link]->data2);
return 0;
}
Output:
30
B
Self Referential Structure with Multiple Links:
Self referential structures with multiple links can have more than one self-pointers. Many complicated
data structures can be easily constructed using these structures. Such structures can easily connect to more
than one nodes at a time. The following example shows one such structure with more than one links.
#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
[Link] = 10;
struct node ob2; // Node2
// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
[Link] = 20;
struct node ob3; // Node3
// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
[Link] = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
// Accessing data of ob1, ob2 and ob3 by ob1
printf("%d\t", [Link]);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob2
printf("%d\t", ob2.prev_link->data);
printf("%d\t", [Link]);
printf("%d\n", ob2.next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob3
printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", [Link]);
return 0;
}
Output:
10 20 30
10 20 30
10 20 30
In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self referential
structure ‘node’. And they are connected using their links in such a way that any of them can easily access
each other’s data. This is the beauty of the self referential structures. The connections can be manipulated
according to the requirements of the programmer.
Applications:
Self referential structures are very useful in creation of other complex data structures like:
Linked Lists
Stacks
Queues
Trees
Graphs
Enumerated Data Type:
Another user-defined data type is enumerated data type provided by
ANSI standard . It is defined as follows(syntax).
enum identifier {value1, value2,… ..... valuen};
The “identifier” is a user-defined enumerated data type which can be used to
declare variables
that can have one of these values enclosed with in braces(known as enumeration
constants). Example
enum day {Monday, Tuesday, ..........Sunday};
enum day week_st, week_end;