XII Comp Science Chapter1 Structure Pointers Hsslive
XII Comp Science Chapter1 Structure Pointers Hsslive
Chapter-1
Structures and Pointers
Structure is a user defined data type which representsa collection of logically
related data items.
Defining a structure
Member definition;
Member definition;
---------------------
------------------------
};
For Example:
struct student
int rollno;
char grade;
float percentage;
};
The elements of a structure are accessed using the dot (.) operator or Period
operator.The syntax for accessing elements is,
#include<iostream>
struct student
int rollno;
int m1,m2,m3;
};
int main()
cin>>s.m1>>s.m2>>s.m3;
cout<<"Total="<<s.m1+s.m2+s.m3;
return(0);
Nested Structure
Array Structure
An array is a collection of similar data A structure is a collection of different data
type(Homogeneous) types(Heterogeneous)
The elements of an array are accessed The elements of a structure is accessed using
using an index dot(.) operator
Array is derived data type Structure is user defined data type
Pointer
The data stored in computer occupies a memory cell.Each cell has a unique
address.A pointer points to the address of memory location.It holds the address
of the memory location.
Declaring a pointer
Data_Type *Pointer_Variable;
For Example:
int *ptr;
Initializing a pointer
Ptr=&a;
#include<iostream>
int main()
int a=10;
int *Ptr=&a;
return 0;
Output:
Memory allocation
For example:
pointer_variable=new data_type;
The delete operator is used to free memory allocated using new operator.The
syntax is
delete pointer_variable;
#include<iostream>
int main()
int i,*p;
p=new int[10];
for(i=0;i<10;i++)
cin>>p[i];
for(i=0;i<10;i++)
cout<<p[i]<<"\t";
delete[]p;
return 0;
For example:
ptr=ch;
here ptr points to the address of first array element in ch.To access fifth element
you can use
ch[4] ; or *(ptr+4);
Operations on pointers
For Example;
int a[50];
int *ptr;
ptr - - or - - ptr;
Moves the pointer to the previous address.(If the base address was 1000 the
operation – ptr moves the pointer to 998 memory location ie,1000 – 2.
#include<iostream>
int main( )
int n,sum=0,*mark_ptr,i;
float avg;
mark_ptr=new int;
cin>>n;
for(i=0;i<n;i++)
cin>>*(mark_ptr + i);
sum=sum+*(mark_ptr+i);
avg=(float)sum/n;
cout<<"Average="<<avg;
return 0;
For example:
struct chain {
int val;
chain *p;
};
The structure has two members val and p.The member p is a pointer to a
structure of type chain.
Dynamic array
A dynamic array is an array created during run time using new operator.The
synatx for creating a dynamic array is
For example:
Intializing an array
or
char ch={‘h’,’e’,’l’,’l’,’o’,’\0’};
cin>>s;
Example:
int main()
{ char a[10];
}
Output:
hello