Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

C/C++ programming.

Hello people


Pointers.
What are pointers?
Answer: Pointers are data elements which point at
other data elements by storing their address.
The value pointed by the pointers can be
accessed by the * operator while the value which
the pointer is holding can be accessed by the &
operator.
Pointers basically hold the address of any
particular value.
Pointers are used in C program to access the
memory and manipulate the address

Pointers

Dereference operator(*) is used to declare a
variable as a pointer variable and also access the
value pointed by the pointer called as derefencing.
Reference operator(&) is used to access the
address of the value pointed at or in other words
the value of the pointer element also called as
access by referencing.
Eg: data_type * pointer_variable_name;
int *p;
Consider the following code again, we have done
examples of pointers, but just a revision with
diagrams.

#include <stdio.h>//address of c= 2686784
int main(){
int *pc,c;
c=22;
printf("Address of c:%d\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf(Content of pointer pc:%d\n",pc);
printf(Value of pointer pc:%d\n\n",*pc);
c=11;
printf(Content of pointer pc:%d\n",pc);
printf(Value of pointer pc:%d\n\n",*pc);
*pc=2;
printf(Content of pointer c:%d\n",&pc);
printf("Value of pointer pc:%d\n\n",*pc);
return 0;
}
Address of c: 2686784
Value of c: 22
Content of pointer pc: 2686784
Value of pointer pc: 22
Content of pointer pc: 2686784
Value of pointer pc: 11
Content of pointer pc: 2686784
Value of pointer pc: 2



Commonly made mistakes by programmers:
int c, *pc; pc=c; /* pc is address whereas, c is
not an address. */
*pc=&c; /* &c is address whereas, *pc is not
an address. */
#include <stdio.h>
int main()
{
char c[4];
int i;
for(i=0;i<4;++i)
{
printf("Address of c[%d]=%x\n",i,&c[i]);
}
return 0;
}
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47

Relation between Arrays and Pointers
int arr[4];

Here arr is pointing to first element of array i.e
arr[0].
Hence value within arr is nothing but address of
arr[0] i.e. &arr[0].
Similarly,
&a[1] is equivalent to (a+1) AND, a[1] is
equivalent to *(a+1).
The same can be said about other elements of
arr[].

A pointer can be used to alter the value of an array[]:

#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21
Pointers & Functions.
Now lets see what do we mean by call by value
and call by reference.
When we call functions having normal variables
as parameters the actual values are passed. i.e.
void func1(int a , int b);//function declaration &
definition
func1(3,4); //function call
Here the values 3 and 4 copied to a and b
variables explicitly.




But when we call functions with pointers as
parameters, the reference to the values are
passed rather then the values themselves. i.e
Void func1(int *a , int *b);
func1(&no1,&no2);
Here, the address of the no1 and no2
variables are passed to the pointers, i.e a and
b point to no1 and no2 respectively.
The point is what is the difference in both the
cases.?
Lets see with an example.

There are two programs both containing
functions accepting two arguments.
The functions are capable of swapping
contents of the parameters passed to them on
call.
The first program contains function with
variables passed as parameters while the
second one contains pointers as parameters.
What do you think would be the
outcome????????
Call by value:
#include <stdio.h>
void swap(int a,int b);
int main(){
int num1=5,num2=10;
swap(num1,num2);
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;}
void swap(int a,int b){
int temp;
temp=a;
a=b;
b=temp;}
Call by reference:
#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
swap(&num1,&num2);
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;}
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;}

We might say what is the use of pointers in
functions, we can right away print the values
of num1 and num2 in the function.

Aye, true, but then here comes the data
encapsulation.


Dynamic Memory Allocation
.
The size of an array is unknown to us till the
compile time.
Only when a compiler compiles code written
in a programming language into a executable
form we have an idea of the size of the array
allocated.
The size of array that we have declared
initially can be sometimes insufficient and
sometimes more than required. (user input)
Dynamic memory allocation allows a program
to obtain more memory space, while running
or to release space when no space is required.
C language inherently does not has any technique to
allocate memory dynamically, but there are 4 library
functions under stdlib.h for dynamic memory
allocation.


Function Details
malloc()
Allocates requested size of bytes and returns a pointer first
byte of allocated space
calloc()
Allocates space for an array elements, initializes to zero and
then returns a pointer to memory
free()

dellocate the previously allocated space
realloc()
Change the size of previously allocated space
malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of
specified size and returns a pointer of
type void which can be cast into pointer of any form.
The syntax for malloc () is:
ptr=(int*)malloc(100*sizeof(int));

Here malloc() allocates a block of 200 or 400 bytes
based on int size 2 or 4 bytes respectively and
returns a int pointer to ptr(pointer variable).
ptr points to the first memory location of the
allocated block.


#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i) {
scanf("%d",ptr+i);
sum+=*(ptr+i);}
printf("Sum=%d",sum);
return 0;}
Enter number of elements:5
Enter elements of array:5 4 3 2 1
Sum=15
calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
The syntax for calloc () is:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory
for an array of 25 elements each of size of float, i.e, 4
bytes.

#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: "); scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL) {
printf("Error! memory not allocated.");
exit(0); }
printf("Enter elements of array: ");
for(i=0;i<n;++i) {
scanf("%d",ptr+i);
sum+=*(ptr+i); }
printf("Sum=%d",sum);
free(ptr);
return 0; }
realloc()
If suppose we realize that the previously allocated
memory is insufficient or more than sufficient. Then
what?????????
Then, we can change memory size previously
allocated using realloc ().
The syntax for realloc () is:
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.

#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;}

Enter size of array: 3
Address of previously allocated memory:
149180424
149180428
149180432

Enter new size of array: 9
149180424
149180428
149180432
149180436
149180440
149180444
149180448
149180452
149180456
free()
Dynamically allocated memory with either calloc() or
malloc() is freed using free() explicitly to release
space.
free( data element to be freed);
Pointers.
Endian Big endian Little endian example
Const char *, char const *, char * const, const
char * const, char const * const
2D and 3D pointers representation
Function Pointers

Pointers
#include <iostream>
using namespace std;
int main() {
int a = 1;
char *cptr = (char *) &a;
printf("%d\n", *cptr);
cptr++;
printf("%d\n", *cptr);
cptr++;
printf("%d\n", *cptr);
cptr++;
printf("%d\n", *cptr);
return 0;}

Big endian systems:
0
0
0
1
Little endian systems:
1
0
0
0
Function pointers:
bool func()normal function returning value
bool * func():Function returning bool
pointer.
bool (*) func(): function pointer pointing to
bool function.
Structures
Structure is the collection of variables of different
types under a single name for better handling.

Eg: Lets say we wanna store some information about
person about his/her name,identity card no and salary.
We can create these information separately but, it will
culminate into confusion for storing them separately.
The better approach will be, collection of these
information under single name because all these
information are related to one person.
Structures
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type member;
};
The keyword struct is used for creating a structure.
Data members are all the variables of different types
which are related.

Structures
For the previous example database we can have a structure
like :
struct person {
char name[50];
int id_card_no;
float salary;
};
Here a structure by the name person is created which has 3
data members.
Now we can create as many person structures as we want by
simply using: struct person p1, p2, p[20];(in main function)
Here we have created a struct person p1 and p2.
We have also created an array of structure person consisting
of 20 elements as p[20].
Structures
We can access the data members for each of
these structure instances using the dot
operator as follows:

p1.name
p2.salary
p[3].id_card_no
#include <stdio.h>
struct Distance{
int feet;
float inch;
}d1,d2,sum;
int main(){
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet); /* input of feet for structure variable d1
*/
printf("Enter inch: ");
scanf("%f",&d1.inch); /* input of inch for structure variable d1
*/
printf("2nd distance\n");

printf("Enter feet: ");
scanf("%d",&d2.feet); /* input of feet for structure variable d2 */
printf("Enter inch: ");
scanf("%f",&d2.inch); /* input of inch for structure variable d2 */
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if (sum.inch>12){
++sum.feet;
sum.inch=sum.inch-12; }
printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); /*
printing sum of distance d1 and d2 */
return 0;
}
Output:->
1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances= 15'-5.7"
Three ways of creating structure instances:
Outside main:
struct Distance{
int feet;
float inch;
}d1,d2,sum;
Inside main:
struct Distance{
int feet;
float inch;
}
int main()
{ struct Distance d1,d2,sum;....
}


As a typedef of structure:
typedef struct Distance
{
int feet;
float inch;
} dist;

int main()
{
dist d1,d2,sum;
}

Structures within structures
Now here we have struct complex which has a
member c1,which is a data member of struct
number.
struct complex {
int imag_value;
float real_value;
};
struct number{
struct complex c1;
int real;
}n1,n2;

n1 and n2 can access the members of complex
struct c1 by using the dot operator twice as
follows:

n1.c1.imag_value
n2.c1.real_value
Structures & Pointers
Pointers can be accessed along with structures. A pointer
variable of structure can be created as below:
struct name {
member1;
member2; . . };
int main(){
struct name *ptr;
Here, the pointer variable of type struct name is created.
Structure's member through pointer can be used in two ways:
1.Referencing pointer to another address to access memory
2.Using dynamic memory allocation

Accessing structure's member through pointer.
#include <stdio.h>
struct name{
int a;
float b;};
int main(){
struct name *ptr,p;
ptr=&p
printf("Enter integer: ");
scanf("%d",&(*ptr).a);
printf("Enter number: ");
scanf("%f",&(*ptr).b);
printf("Displaying: ");
printf("%d%f",(*ptr).a,(*ptr).b);
return 0;}
The structure members can also be accessed
by pointers by using the arrow operator

(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b
memory can be allocated dynamically using malloc()
#include <stdio.h>
#include<stdlib.h>
struct name {
int a;
float b;
char c[30];};
int main(){
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
ptr=(struct name*)malloc(n*sizeof(struct name));
for(i=0;i<n;++i){
printf("Enter string, integer and floating number respectively:\n");
scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);}
for(i=0;i<n;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
return 0;}


Structure and Function

Structure can be passed to functions by two methods:
1. Passing by value (passing actual value as argument)
2. Passing by reference (passing address of an argument)
Like normal pointers, when structures are passed by value,
change made in structure variable in function definition
does not reflect in original structure variable in calling
function.
When structure is passed by reference, the address
location of the structure is actually passed.
Also, change made in structure variable in function
definition reflects in original structure variable in the calling
function.
Remember that function taking structure data type as a
parameter should be declared after the structure
declaration.
Lets look at the example for each type.



struct student{
char name[50];
int roll;};
void Display(struct student stu);
int main(){
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1);
return 0;}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);}


#include <stdio.h>
struct distance{
int feet;
float inch;};
void Add(struct distance d1,struct distance d2, struct distance
*d3);
int main(){
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");


printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);
printf("\nSum of distances = %d\'-%.1f\"",dist3feet,
dist3inch);
return 0;}
void Add(struct distance d1,struct distance d2, struct distance
*d3) {
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) {
d3->inch-=12;
++d3->feet; }
}

Unions:
Similar to structures.
Similarity:
Declaration & definition.
Three types of creating instances.
Accessing the data members either through
simple instances or pointer instances.
Working in the same manner as structure
instances work.
Two ways of passing as parameters.
Unions:
What is the difference between them..??
Its in memory allocation between union and
structure.
The amount of memory required to store a structure
variables is the sum of memory size of all members.
Whilst, the amount of memory required to store a
union variable is the memory required for largest
element of an union.
Example is on its way..


#include <stdio.h>
union job { //defining a union
char name[32];
float salary;
int worker_no;
}u;
struct job1 { //defining a structure
char name[32];
float salary;
int worker_no;
}s;
int main(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
}

Output:
size of union = 32
size of structure = 40


#include <stdio.h>
union job {
char name[32];
float salary;
int worker_no;
}u;
int main(){
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
return 0;
}

Output:
Enter name
Hillary
Enter salary
100000
Displaying Name: ******(any garbage value)
Salary: 100000

This means we can access only one data member of a union
variable at a time while all other data members are holding
garbage values.
Also amongst all the data members the most recent member
to be updated or assigned with value will be available.

Enumeration

An enumeration is a user-defined data type which consists
of integral constants and each integral constant is give a
name
Syntax for enumeration is:
enum type_name{ value1, value2,...,valueN };

By default value1=0, value2=1.
We can also have our own values assigned as follows:
enum houses{
agni=1;
vayu=2;
prithvi=3;
aakash=4;
};
Enumerated variables are declared similar to structures
and unions:

#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday,
thursday, friday, saturday};
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}

Output
4 day

You might also like