3. • ‘Pointer’ is a variable that
contains a memory address of
other variable (does not contain
a actual data).This is why we
call it “Pointer” since it is used
to POINT other variable.
What Is
pointer?
4. Some situations where pointers can be used are
To return more than one value from a function
To pass arrays and strings more conveniently from one function
to another
To manipulate arrays easily by moving pointers to them
instead of moving the arrays itself
To allocate memory and access it
(Direct Memory Allocation)
5. 5
int main ()
{
int a;
int b;
int c;
…
int* ptr;
a = 1000;
b = 2000;
c = 3000;
}
1000 2000 3000
int a int b int c
NUL
3004 3006
int* ptr
1004 1006 1008 1012
6. 6
int main ()
{
int a;
int b;
int c;
int* ptr;
a = 1000;
b = 2000;
c = 3000;
ptr = &a;
}
1000 2000 3000
1004 1006 1008 1012
int a int b int c
1004
3004 3008
int* ptrmemory
address of ‘a’
7. int *
p;
int*
p;
int
*p;
• Thus, the character * can appear anywhere between the
data type name and the variable name.
• Syntax:
data_type *var_name;
7
8. C provides
two operators
to work with
pointers.
(&) the
address of
operator
(*) the
dereferencing
is a unary operator that
returns the address of its
operand.
For example, given the
statements:
int x;
int *p;
The statement:
p = &x;
assigns the address of x
to p. That is, x and the
value of p refer to the
same memory location
referred to as indirection
operator
refers to the object to which
its operand (that is, the
pointer) points.
For example, given the
statements:
int x=25,*p;
p=&x
25
Xp
9. • Consider the following statements.
1. num = 78;
2. p = #
3. *p = 24;
9
10. Assignment
• The value of one pointer variable can be assigned to another
pointer variable of the same type.
• Example:
• Note:
Any changes made to *p automatically change the value
of *q, and vice versa.
int *p,*q, i=5;
q=&i;
p=q;
11. comparison
• Two pointer variables of the same type can be compared
for equality, and so on.
• Example : int *p,*q, i=5;
q=&i;
p==q;
p!=q;
evaluates to true if p and q have
the same value that is, if they point
to the same memory location.evaluates to true if p and q
point to different memory
locations.
12. Decrement and increment
• Integer values can be added and subtracted from a
pointer variable.
• ++ increments the value of a pointer variable by the size
of the memory to which it is pointing.
• Similarly, -- the value of a pointer variable by the size of
the memory to which it is pointing.
13. • Example :
• Let us assume that var is stored at the address 1000
• Then ptr_var has the value 1000 stored in it. Since integers
are 2 bytes long, after the expression “ptr_var++;” ptr_var
will have the value as 1002 and not 1001
int var,*ptr_var;
ptr_var=&var;
var=500;
Ptr_var++;
14. a &a[0]
‘a’is a pointer only to the first element, not the whole array
same
15.
16. #include<stdio.h>
void main()
{
static int ary[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9,10};
int i;
for (i = 0; i < 10; i ++)
{
printf(“ni=%d,ary[i]=%d,*(ary+i)=%d“,i,
ary[i],*(ary + i));
printf(“&ary[i]= %X,ary+i=%X”,&ary[i],ary+i);
/* %X gives unsigned hexadecimal */
}
}
17.
18.
19. • The malloc() function dynamically allocates memory
when required. This function allocates ‘size’ byte of
memory and returns a pointer to the first byte or NULL if
there is some kind of error.
20.
21. • calloc is similar to malloc, but the main difference is
that the
• values stored in the allocated memory space is zero by
default
calloc requires two arguments
The first is the number of variables you'd like to allocate
memory for
The second is the size of each variable
22.
23. • You've allocated a certain number of bytes for an array
but later find that you want to add values to it.You could
copy everything into a larger array, which is inefficient, or
you can allocate more bytes using realloc, without losing
your data.
realloc takes two arguments
The first is the pointer referencing the memory
The second is the total number of bytes you want to reallocate
27. • free() function can be used to de-allocates (frees) memory
• when it is no longer needed.
Syntax:
void free(void *ptr );
• This function de allocates the space pointed to by ptr,
• freeing it up for future use.
• ptr must have been used in a previous call to malloc(),
• calloc(), or realloc().
28.
29. A function in C can have a value, a side
effect, or both
• The side effect occurs before the value is returned.
• The function’s value is the value of the expression in the
return statement.
• A function can be called for its value, its side effect, or both.
30.
31. • The general syntax of a function in C is :
• The type_specifier specifies the data type of the value, which
the function will return.
• A valid function name is to be assigned to identify the
function
• Arguments appearing in parentheses are also termed as
formal parameters.
32. //Prototype declaration
void greeting();
int main()
{
greeting();
return 0;
} // main
Void greeting()
{
printf(“HELLO WORLD”);
return ;
} //greeting()
Declaration
is coded
first
Definition is
after the call
Call is in the
statement
sections
33.
34. The type of the expression in the return
statement must match the return type in the
function header.
. Only one value can be returned by a
function
35. • Formal parameters are variables that are declared in the header of
the function definition.
• Actual parameters are the expressions in the calling statement.
• The formal and actual parameters must match exactly in type, order,
and number. Their names, however, do not need to be the same.
36. int square(int x);
Int main()
{
Int I
For(i=1;i<10; i++)
{
printf(“n square of %d is %d:”, i, square(i));
}
int square(int x)
{
int j;
j=x*x;
return(j);
}
Actual
argument
Formal
argument
37. • Local Variables
• Declared inside a function
• Created upon entry into a block and destroyed upon exit from the
block
• Formal Parameters
• Declared in the definition of function as parameters
• Act like any local variable inside a function
• Global Variables
• Declared outside all functions
• Holds value throughout the execution of the program
38. float pi=3.1415;
void area( int rad);
int main()
{
float radius;
printf("nEnter the radius of Circle : ");
scanf("%d", &radius);
area(radius);
Return 0;
}
Void area( int rad)
{
int area;
area=pi*rad*rad;
}
Global variable
Formal parameter
Local variable
39. Every C variable has a characteristic called as a storage class
The storage class defines two characteristics of the variable:
• Lifetime – The lifetime of a variable is the length of
time it retains a particular value
• Visibility – The visibility of a variable defines the parts of a
program that will be able to recognize the variable
41. • Scope Rules - Rules that govern whether one piece of
code knows about or has access to another piece of
code or data
• The code within a function is private or local to that
function
• Two functions have different scopes
• One function cannot be defined within another function
43. When arguments are
passed to the called
function, the values
are passed through
temporary variables
44. • In call by
reference, the
function is
allowed access
to the actual
memory
location of the
argument and
therefore can
change the
value of the
arguments of
the calling
routine
46. • A pointer variable can be passed as a parameter to a function
either by value or by reference.
• In the function pointerParameters, both p and q are pointers.
The parameter p is a reference parameter; the parameter q is
a value parameter.
• Furthermore, the function pointerParameters can change the
value of *q, but not the value of q. However, the function
pointerParameters can change the value of both p and *p.
47.
48. The string is any sequence of characters surrounded by
double quotes.
• Strings are arrays of characters terminated by the NULL
(‘0’) character.
• The ‘0’ null character is automatically added in the
internal representation of a string.
49. A typical string variable declaration is:.
char str[10];
str is a character array variable that can hold a maximum
of 10 characters including the null terminator.
50. String I/O operations are carried out using functions from the
standard I/O library called stdio.h
The gets() function is the simplest method of accepting a
string through standard input
Input characters are accepted till the Enter key is pressed
The gets() function replaces the terminating ‘n’ new line
character with the ‘0’ character
Syntax :
gets(str);
51. The puts() function is used to display a string on the standard output
device.
Syntax :
puts(str);
The scanf() and printf() functions are used to accept and display mixed
data types with a single statement.
The syntax to accept a string is as follows:
scanf(“%s”, str);
The syntax to display a string is as follows:
printf(“%s”, str);
52. Functions for handling strings are found in the standard
header file string.h. Few of the operations performed by
these functions are:
• Concatenating strings
• Comparing strings
• Locating a character in a string
• Copying one string to another
• Calculating the length of a string
53. Joins two string values into
one.
Syntax:
strcat(str1, str2);
Concatenates the str2 at the
end of str1
The function returns str1
54. Compares two strings and returns an integer value based
on the results of the comparison.
Syntax:
strcmp(str1, str2);
The function returns a value:
• Less than zero if str1<str2
• Zero if str1 is same as str2
• Greater than zero if str1>str2
55.
56. Determines the occurrence of a character in a string.
Syntax:
strchr(str, chr);
The function returns a value:
• Pointer to the first occurrence of the character
(pointed by chr) in the string, str
• NULL if it is not present
57.
58. Copies the value in one
string onto another
Syntax:
strcpy(str1, str2);
The value of str2 is copied
onto str1
The function returns str1
59. Determines the length of a
string
Syntax:
strlen(str);
The function returns an
integer value for the
length of str
60. When an array is passed as an argument to a function,
only the address of the array is passed
The array name without the subscripts refers to the
address of the array
void main()
{
int array[10];
.
.
fn_ary(array);
.
.
}
61. #include<stdio.h>
void main()
{
int num[5], ctr, sum=0;
int sum_arr(int num_arr[]); /* Function declaration */
clrscr();
for(ctr=0;ctr<5;ctr++) /* Accepts numbers into the array */
{
printf("nEnter number %d: ", ctr+1);
scanf("%d", &num[ctr]);
}
62. sum=sum_arr(num); /* Invokes the function */
printf("nThe sum of the array is %d", sum);
getch();
}
int sum_arr(int num_arr[]) /* Function definition */
{
int i, total;
for(i=0,total=0;i<5;i++) /* Calculates the sum */
total+=num_arr[i];
return total; /* Returns the sum to main() */
}
Sample output of the
program
Enter number 1: 5
Enter number 2: 10
Enter number 3: 13
Enter number 4: 26
Enter number 5: 21
The sum of the array
is 75
63. #include<stdio.h>
#include<string.h>
void main()
{
char lines[5][20];
int ctr, longctr=0;
int longest(char lines_arr[][20]);
/* Function declaration */
clrscr();
for(ctr=0;ctr<5;ctr++)
/* Accepts string values into the array */
{
printf("nEnter string %d: ", ctr+1);
scanf("%s", lines[ctr]);
}
64. longctr=longest(lines);
/* Passes the array to the function */
printf("nThe longest string is %s", lines[longctr]);
getch();
}
int longest(char lines_arr[][20]) /* Function definition */
{
int i=0, l_ctr=0, prev_len, new_len;
prev_len=strlen(lines_arr[i]);
/* Determines the length of the first element */
65. for(i++;i<5;i++)
{
new_len=strlen(lines_arr[i]);
/* Determines the length of the next element */
if(new_len>prev_len)
l_ctr=i;
/* Stores the subscript of the longer string */
prev_len=new_len;
}
return l_ctr;
/* Returns the subscript of the longest string */
}
Sample output of the program
Enter string 1: The
Enter string 2: Sigma
Enter string 3: Protocol
Enter string 4: Robert
Enter string 5: Ludlum
The longest string is Protocol
66. • Structure is another user defined data type which allows
you to combine data items of different kinds.
• The variables in a structure can be of different types:
Some can be int, some can be float, and so on.
• The data items in a structure are called the members of
the structure.
67.
68. • struct part part1;
• defines a variable, called part1, of type structure part.
• This definition reserves space in memory for part1.
Model no part no cost
10031001 1007 1011
part1
69. • Other ways of declaring structures variables:
struct stud
{
char name[10];
int age;
};
main()
{
struct stud s1, s2;
}
struct stud
{
char name[10];
int age;
} s1, s2;
main()
{
}
struct
{
char name[10];
int age;
} s1 s2;
main()
{
}
70. • Members can be accessed using something called the
dot operator. syntax is
Structure_var_name.element_name;
• Here’s how the first member is given a value:
part1.modelnumber = 6244;
• .Is called member access operator
73. Structures can also be nested in such a way that an element
of a structure is itself another structure:
struct subject
{
char name[20];
float marks;
};
struct friend
{
char name[10];
int age;
subject fsub;
}
Int main()
{
friend frnd1,frnd2;
frnd1.name=“amir”;
frnd2.name=areeb;
frnd1.fsub.name=“computer”;
frnd2.fsub.name=“maths”;
frnd1.fsub.marks=85;
frnd2.fsub.marks=80;
}
74. • A structure variable can be passed as an argument to a
function
• This facility is used to pass groups of logically related
data items together instead of passing them one by one
• The type of the argument should match the type of the
parameter
75.
76. A common use of structures is in arrays of structures
A structure is first defined, and then an array variable of
that type is declared
Example:
struct student class_a[50];
To the access the variable author of the fourth element of
the array books:
class_a[4].marks;
77. • Structure arrays are initialized by enclosing the list of values of its
elements within a pair of braces
• Example
struct unit
{ char ch;
int i;
};
struct unit series [3] =
{ {‘a’, 100}
{‘b’, 200}
{‘c’, 300}
};
78. • Memory representation of arrays of structure
1001 1004 1007 1010
0 1 2
series
Ch i Ch i Ch i
1002 1004 1005 1007 1008 1010
79. • Sorting involves arranging the array data in a specified
order such as ascending or descending
• Data in an array is easier to search when the array is
sorted
• There are two methods to sort arrays – Selection Sort
and Bubble Sort
• In the selection sort method, the value present in each
element is compared with the subsequent elements in
the array to obtain the least/greatest value
80.
81. main()
{
int arr[] = {15,2,20,10,1};
int temp=0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
} }
}
86. All I/O operations in C are carried out using functions
from the standard library
This approach makes the C file system very powerful
and flexible
I/O in C is unique because data may be transferred in its
internal binary representation or in a human-readable
text format
87. • When the program is terminated, the entire data is lost in
C programming. If you want to keep large volume of
data, it is time consuming to enter the entire data. But, if
file is created, these information can be accessed using
few commands.
88. • Stream is not a hardware it is linear queue which
connect file to program and passes block of data in both
direction .So it is independent of devices which we are
using. We can also define stream as source of data. This
source can be
•
• (a) A file
• (b) Hard disk or CD, DVD etc.
• (c) I/O devices etc.
89. • In c programming language there are two type of stream.
(a) Text streams
(b) Binary streams
90. • A text stream is a sequence of characters that can be
organized into lines terminated by a new line character
Binary streams are a flat sequence of bytes, which do
not have any flags to indicate the end of file or end of
record
The end of file is determined by the size of the file
91. A file can refer to anything from a disk file to a terminal or
a printer
A file is associated with a stream by performing an open
operation and disassociated by a close operation
When a program terminates normally, all files are
automatically closed
When a program crashes, the files remain open