History :
`C' programming language invented by Kernighan & Ritchie way back 1972,
basically called as `B' language.
Data Type :
A variable is a symbolic name for a computer memory location, while declaring a
variable the programmer must declare the type of data or information to be
stored in a variable and the size of memory it is going to occupy. Primitive
data types are those are not composed, it also known as fundamental data types.
1.
Integers : Integers are whole numbers with a machine dependent
range of values. A good programming language as to support the programmer by
giving a control on a range of numbers and storage space. C has 3 classes of
integer storage namely short int, int and long int. All of these data types have
signed and unsigned forms. A short int requires half the space than normal
integer values. Unsigned numbers are always positive and consume all the bits
for the magnitude of the number. The long and unsigned integers are used to
declare a longer range of values.
2.
Characters : A single character can be defined as a defined as a
character type of data. Characters are usually stored in 8 bits of internal
storage. The qualifier signed or unsigned can be explicitly applied to char.
While unsigned characters have values between 0 and 255, signed characters have
values from –128 to 127.
3.
Floating point – Floating
point number represents a real number with 6 digits precision. Floating-point
numbers are denoted by the keyword float. When the accuracy of the
floating-point number is insufficient, we can use the double to define the
number. The double is same as float but with longer precision. To extend the
precision further we can use long double, which consumes 80 bits of memory
space.
All C
Compilers accept the following fundamental data types
1.
|
Integer
|
int
|
2.
|
Character
|
char
|
3.
|
Floating Point
|
float
|
4.
|
Double precision floating point
|
double
|
5.
|
Void
|
void
|
Size
and Range of Data Types on 16 bit machine.
Type
|
SIZE (Bits)
|
Range
|
Char or Signed Char
|
8
|
-128 to 127
|
Unsigned Char
|
8
|
0 to 255
|
int or Signed int
|
16
|
-32768 to 32767
|
Unsigned int
|
16
|
0 to 65535
|
Short int or Signed short int
|
8
|
-128 to 127
|
Unsigned short int
|
8
|
0 to 255
|
long int or signed long int
|
32
|
-2147483648 to 2147483647
|
Unsigned long int
|
32
|
0 to 4294967295
|
float
|
32
|
3.4 e-38 to 3.4 e+38
|
double
|
64
|
1.7e-308 to 1.7e+308
|
long double
|
80
|
3.4 e-4932 to 3.4 e+4932
|
Constant or Literals–
A data item does not change during execution of a program is called a constant
or literals. Constant or literals can be numeric – Integer (int) type or
fractional (float or double), character or string. e.g. 200, “hello”, 45.0F,
444.4545, TRUE, FALSE
Identifiers or variables–
Symbolic names used for various data items in programs
known as identifiers. Identifiers also can be defined as user defined name given
to memory boxed to store data or information.
Rules for naming identifiers.
1. Must start with an
alphabet.
2. A numeric digit allowed.
3. No space or symbols are
allowed except an underscore.
4. No keyword can be use as
identifiers.
Volatile Variable :
A volatile variable is the
one whose values may be changed at any time by some external sources.
Example:
volatile int num;
The value of data may be
altered by some external factor, even if it does not appear on the left hand
side of the assignment statement. When we declare a variable as volatile the
compiler will examine the value of the variable each time it is encountered to
see if an external factor has changed the value.
User defined type declaration :
In C language a user can
define an identifier that represents an existing data type. The user defined
datatype identifier can later be used to declare variables. The general syntax
is
Example:
typedef int Integer;
typedef float Fpoint;
Here
Integer symbolizes int and Fpoint symbolizes float. They can be later used to
declare variables as follows:
Example:
Integer age;
Fpoint
Saray,tax;
enum
identifier {value1, value2 …. };
The
identifier is a user defined enumerated datatype which can be used to declare
variables that have one of the values enclosed within the braces. After the
definition we can declare variables to be of this ‘new’ type as below.
Example:
enum
col {RED,BLUE,GREEN,..};
enum
day CR,CG;
CR
=RED;
CG =
GREEN;
Declaring Variable as Constant
The
values of some variable may be required to remain constant through-out the
program. We can do this by using the qualifier const at the time of
initialization.
Example:
const
int val = 20;
const
value = 30;
Defining
a Symbolic Constant using #define directive A symbolic constant value can be
defined as a preprocessor statement and used in the program as any other
constant value.
Example:
#
define [valid variable name] value
#
define MAX 100
#
define pi 3.14159
These
values may appear anywhere in the program, but must come before it is referenced
in the program. It is a standard practice to place them at the beginning of the
program.
Declaration of Storage Class
Variables in C have not only
the data type but also storage class that provides information about their
location and visibility. The storage class divides the portion of the program
within which the variables are recognized.
auto :
It is a local variable known only to the function in which it is declared. Auto
is the default storage class.
static :
Local variable which exists and retains its value even after the control is
transferred to the calling function.
extern :
Global variable known to all functions in the file
register :
Social variables, which are stored in the register.
Storage Class
|
Storage
|
Default Initial Value
|
Scope
|
Life
|
Automatic (syntax: auto) (All data types)
|
Memory
|
Unpredictable Garbage value
|
Local to the block in which the
variable is defined
|
Till the control remains within
the block in which it is defined
|
Register (syntax: register) (Only integers)
|
CPU
Registers
|
Unpredictable Garbage value
|
Local to the block in which the
variable is defined
|
Till the control remains within
the block in which it is defined
|
Static
(syntax: static) (All data types)
|
Memory
|
Zero
|
Local to the block in which the
variable is defined
|
Value of the variable persists
between different function calls
|
External (syntax: extern) (All data types)
|
Memory
|
Zero
|
Global
|
As long as the program's
execution does not come to an end
|
Instance variable -
Instance variables are any variables that are defined in a constructor function
and that are copied into each object instance of that constructor. All object
instances have their own copies of instance variables. The significance of an
instance variable is that every object instantiated from that class contains
its own copy of all instance variables.
Global Variable -
A variable whose value can be accessed and modified by any statement in an
application, and not merely within a single routine in which it is defined.
Variables declared just in side the class known as global variable.
class
testing
{
int
a, b; //global variable
}
Local Variable - A
variable that is accessible only within a function or procedure. Other
procedures or functions cannot access this variable's data. Use global variables
to share data across many procedures and functions, or private variables to
share data with the functions you call.
Keyword –
Reserved words that convey meaning to the computer. Used to write programming
syntax. A programming syntax or statement should have at least one keyword. e.g.
class, int, if, for.
Statements:
Statements consist of tokens,
expressions, and other statements. A statement that forms a component of another
statement is called the “body” of the enclosing statement. Each statement type
given by the following syntax is discussed in this chapter.
Compound Statements (Blocks) - A compound statement consists of zero or more
statements enclosed in curly braces ({ }). A compound statement can be used
anywhere a statement is expected. Compound statements are commonly called
“blocks.”
Operators -An
operator is a symbol or letter, which makes the computer perform specific
operation in a programming statement.
arithmetic operator -
Operators that perform
numeric calculations known as arithmetic operators are: + (addition), –
(subtraction), * (multiplication), / (division) and % (modulus).
Relational operator -
An operator that manipulates
numeric and other values to produce a logical result. The relational operators
are <, >,= =, <=, >=, and !=.
Unary operator -
The unary assignment operators, use two operand instead of one, for the
increment (++) and decrement (– –) operators. Its also call
increment/decrement operator. a++, a--, a+=10.
Ternary Operator –
Can be used to replace
certain of if – else-if statement. Its require three operands to work on. It
represent by the ? and : symbols. Expression1?Expression2:Expression3 e.g. tax =
salary>10000?salary*0.05 : 0; (if variable salary stored more than 10000 then
tax variable will calculated 5% of salary otherwise tax will be).
Logical Operator -
An operator that produces a
logical result (true or false); sometimes called a Boolean operator. The logical
operators are used for expression grouping, NOT or ! (negation), AND (Creates a
Boolean behavior that represents the logical AND of the given behaviors. The
behavior's value is true when both b1 and b2 are true; otherwise,
it is false. OR (Creates a Boolean behavior that represents the logical OR of
the given behaviors. The behavior's value is true when either b1 or b2
are true; otherwise it is false).
Binary Operator -
This operator do the binary operations between two or more variables. Also known
as bits operator. The bitwise operators perform bitwise-AND (&),
bitwise-exclusive-OR (^), and bitwise-inclusive-OR () operations. E.g.
101 & 100 = 100 (Multiplication). 101 ! 100 = 101 (Addition). 101 ^ 100 = 001(If
one bit is 0 and the other bit is 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0). Right shift >> Left
shift << (The value of a right-shift expression e1 >> e2
is e1 / 2e2, and the value of a left-shift expression e1
<< e2 is e1 * 2e2).
Function Call by value -
When a simple type passed to a method, as a copy of
the argument is being made and passed to the function is known as call by
value, any changes made to the parameter inside the function do not affect
the original. A functions parameter list also known as signature.
void
test()
{
int a=10,b=20;
int s=sum(a, b);
}
Function call by reference - When an object is passed as an argument to a method
it is passed by reference. A reference to an argument is passed as
parameter, the value of the argument is not passed. This method is called
call by reference.
struct
testing
{
int a, b;
}*test;
void
tester(struct *t)
{
printf("%d %d ",t->a,t->b);
}
void
main() // main function
{
tester(test);
}
Pure function -
Pure function or accessor methods return information to the caller about a state
of an object without changing the state.
Impure function -
Impure function or mutator
methods return information to the caller about a state of an object by changing
the state.
actual parameter -
The actual value that is
passed into the method by a caller. Actual arguments (those supplied by the
caller) are evaluated. Caller – sum(a, b)
formal parameter -
The identifier used in a
method to stand for the value that is passed into the method by a caller.
Receiver – int sum(int x, int y)
Comment
- A comment is a remark from programmer to explain some aspect of the code to
who is reading the source code. Comments can be anything including or excluding
programming syntax as compiler ignore it. a) Single line comments - Comments
followed the // symbols
b) Multiline Comments – The
are used for comments spread over many line. They begin with /* and end with */.
printf() -
Print formatted output to the
standard output stream. A format specification, which consists of optional and
required fields. Each field of the format specification is a single character or
a number signifying a particular format option. The simplest format
specification contains only the percent sign and a type character : %d –
Integer, %f – Float, %u – Unsigned, %c – Character, %s – String. %3d – Integer 3
digit long. %5.2f – 1 whole no, one decimal point and 2 decimal places( 99.99).
%30s – Right align. %-30s – Left align. Some of escape character - \n – new
line. \t – 8 space tab.
Scanf() -
Read formatted data from the
standard input stream. The scanf function reads data from the standard
input stream and writes the data into the variable given by argument.
Each argument must be a pointer to a variable (address) of a type that
corresponds to a type specifier in format(see printf) .
If – else if – else -
The if keyword is used to
execute a statement or block of statements when its associated expression
evaluates to true. An if statement may also have an alternative else if
or else clause. If the expression defined by the if statement evaluates to
false, then control transfers to the statement (or block of statements)
following the else if or else keyword. If the expression defined by the
if statement evaluates to true, then control transfers to the first
statement following the if keyword. Multiple conditional expression can be
written in if or else if statement separated by logical operator but
there is no expression written in else.
if ( num
< 1000 ) //when num is below 1000
t=10;
else if
( num <5000) // When num is equal or over 1000 but below 5000
t=100;
else
t=1000
switch -
The switch keyword is used
along with the keyword case, and sometimes the keyword default, to create
a conditional statement. In a switch statement, the switch keyword
is followed by an expression within parentheses. Once the expression has been
evaluated, its value is compared against the label following each case
statement within the switch statement body. When a label has the same
value, the lines following that case statement are executed. An optional
default label is included within the body of a switch statement when there is no
guarantee that the labels provided by each case statement are the only
values the switch expression may evaluate to.
switch(variable)
{
case 1 : printf(“Switch-case”); break;
default : printf(“Not a Value”;
}
The break keyword is
also, at times, used within the body of a switch statement. Once the lines
following a case statement have executed, the break statement is included
to jump over the remaining body of the switch condition. Without a break
statement, subsequent case statements would continue being evaluated, and
eventually the default statement, if one were included, would execute.
Difference between if-else-if-else and switch
1. switch-case -
switch-case can only check of equality. switch only looks for match
between the values of the expression with one of its case constant
values.
2. No two case
constant can have identical values.
3. Use of switch
is more convenient than multiple nested if. When the case constant match
with criteria given computer start from that point continue performing
each case even its not satisfied the condition, so its required jump
statement like break to jump from the table.
4. Thus its run
faster than if construct. In switch-case no floating point constant
allowed.
|
|
1.
if-else-if-else - if can evaluate any type, if-else statement uses
series of expression involving unrelated variables.
2. No jump
statement can be given for if statement.
3. It check each
condition even after it’s found its match, so it’s slower than
switch-case.
4. In
if-else-if-else floating point constant can be used as a condition.
|
for
- The for keyword is used to
create a loop construct. An initialization section, an expression section, and
an update section immediately follow the keyword. A semicolon separates each
section, and all appear together within at least one set of parentheses. The
initialization section allows the programmer to declare one or more local loop
variables with initial values. The expression or final value section contains an
expression that is evaluated to determine whether the loop should continue or
how long it should continue. A true result allows the loop to continue; a false
result allows control to transfer to the statement following the loop body. The
update section allows to increment loop counters or perform other updates.
Typically, the update section is used to increment or decrements whatever loop
counters the programmer defines. e.g. for( int i = 0; i< 10; i++ )
while - The while keyword is
used to create a loop construct. In a while loop, the expression in parentheses
immediately following the keyword is evaluated, and if the result is true, the
statements appearing within the loop body are executed. If multiple statements
make up the body of the loop, they must be enclosed with curly braces. Once the
loop body has executed, control transfers back to the top of the loop where the
test is performed again, and the execution of the loop body is repeated until
the value of the expression evaluates to false. While is a entry centered loop
as it check the condition and then perform the body. e.g. while(i++<10)
do-while - The do keyword is
used as part of a do-while loop. Unlike the other, more commonly used loop
constructs, a do/while loop expression is evaluated only after the block of code
within its body has been executed. Thus, you are ensured that the code within
the loop body is executed at least once, even if the expression tested causes
the loop to end. . do-while is an exit centered loop as it does not check any
condition but perform the body once and then check the condition. A semicolon is
required after the condition (while) in a do/while loop.
int i=1
do
{
printf("Printing at least once";
i++;
} while ( i <= 10 );
while – do-while Difference
1. while - while
is entry centered loop.
2. while check
its condition and if satisfied then it performed the body else it comes
out of the loop statement and proceeds further.
|
|
1. do-while -
do-while is a exit centered loop.
2. do-while,
start with do and does not check any condition when computer performed
the loop body first time, but check the condition at the below, which
given in while, so even condition is not satisfied.
|
Jump Statement – Jump
statement used to transfer control to another part of the program. break,
continue worked as jump statement.
break - Statement used to
terminate the current loop or a sequence in switch statement.
while(a<10)
{
if(a==5)
break;
}
continue
– Used only in loop to terminate that particular process and transfer control to
the loop conditional expression.
while(a<10)
{
if(a==5)
continue;
}
break and continue Difference
1. break can be
used as a jump statement in any type of loops and switch-case.
2. break jump
directly out of the body of the loop or switch-case statement and
follows the next statement onwards.
|
|
1. continue can
be used in loop but not in switch-case.
2. continue
transfer control to conditional expression not quite the loop.
|
Type Casting :
Converting an expression of a
given type into another type is known as type-casting. We have already
seen some ways to type cast:
Implicit conversion :
Implicit conversions do not
require any operator. They are automatically performed when a value is copied to
a compatible type. For example:
short
a=2000;
int
b;
b=a;
Explicit conversion
: Many conversions, specially
those that imply a different interpretation of the value, require an explicit
conversion. We have already seen two notations for explicit type conversion:
functional and c-like casting:
short
a=2000;
int b;
b =
(int) a; // c-like cast notation
b = int (a); //
functional notation
Array
- An array is a group of same typed variables that are referenced by a common
name. Arrays can be any typed and one or more dimensions. A particular element
can be addressed by array name and index of the array enclosed in third bracket
([]). Array can be declared with its initial values or can be defined with the
size and can input the values latter. An array index start from 0 by default.
int x[]={1,2,3,4}; int a[10];
structure
– Structure is groups the variables in a single record. E.g. struct personal {
char name[20], int age;}per, per1;
personal
is struct type name and
per / per1 are structure variables, name and age are
the structure elements. Structure type and variables both are optional, but one
of the two must appear. Structure type used to create multiple copies and can
not be used directly where structure variable can be used directly like
per.name.
Header Files
- File containing predefined compile-time constants or functions. This can be
inserted at any part of the program.
#include
- Directive tells the preprocessor to treat the contents of a specified file as
if those contents had appeared in the source program at the point where the
directive appears. You can organize constant and macro definitions into include
files and then use #include directives to add these definitions to any
source file.
Function-like macros
can take arguments, just like true functions. To define a macro that uses
arguments, you insert parameters between the pair of parentheses in the macro
definition that make the macro function-like. The parameters must be valid C
identifiers, separated by commas and optionally whitespace.
Example:
#define
min(X, Y) ((X) < (Y) ?
(X) : (Y))
void
main()
{
int
X,Y,Z ;
X=10 ;
Y=20 ;
Z =
min(a, b); // invoking the macro
printf("\n Minimum of %d and %d = %d ",X,Y,Z);
}
Macro
& Function
·
Macro
consumes less time. When a function is called, arguments have to be passed to
it, those arguments are accepted by corresponding dummy variables in the
function, they are processed, and finally the function returns a value that is
assigned to a variable (except for a void function). If a function is invoked a
number of times, the times add up, and compilation is delayed. On the other
hand, the macro expansion had already taken place and replaced each occurrence
of the macro in the source code before the source code starts compiling, so it
requires no additional time to execute.
·
Function consumes less memory. While a function replete with macros may look
succinct on surface, prior to compilation, all the macro-presences are replaced
by their corresponding macro expansions, which consumes considerable memory. On
the other hand, even if a function is invoked 100 times, it still occupies the
same space. Hence function is more amenable to less memory requirements.
<stdio.h> – Standard input output header file
having following function –
gets()
– Gets a string from stdin.
puts()
– print the output to the stdout.
getchar()
: accept a character with confirmation.
fopen() ,fclsoe(), fwrite(), fread():
open, close, write and read a data file. These function also part of header
file - scanf(), printf(),fopen(), struct etc.
<conio.h> – Console input and output header
file. Some of following function of this header file –
clrscr()
: To clear the user screen.
getch()
: Wait until a character pressed & without prompting on the screen continue
further. Also used to input a character. e.g. getch() or a=getch().
getche()
: Wait until a character pressed & with displaying it on the screen continue.
Also used to input a character. e.g. getche() or a=getche()
<string.h> – Provide different string function,
such as :
strcat()
: Concatenate two string. e.g. strcat(a,c).
strcmp()
: Compare two string and return zero if true. x=strcmp(a,c).
strcmpi()
: Compare two string, case intensive.
strcpy()
: Copy source string to
target. e.g. strcpy(target,source).
strlen() : To get
the length of a string. e.g. x=strlen(c).
strlwr()
: To convert a string to lowercase. e.g. strlwr(c).
strrev()
: Reverse the character in a string. e.g. strrev(c).
strupr() : Convert
a string to uppercase. strupr(c).
<math.h>
- Used to provide function for mathematical operation -
log() :
To get a natural log of a
given no.
pow() :
To execute the x^n. e.g.
b=(x,3) will give x^3 answer
sin() :
To get the sine of an angle.
e.g. sin(ivar or fvar)
sqrt() :
Find square root of a no.
tan()
: To find tan of a
angle.
<ctype.h> - Used to provide function for
character input.
tolower() :
To change a character to
lowercase. eg._tolower(a)
toupper() :
To change a character to
uppercase. e.g. _toupper(a)
isascii(), islower(), isupper(), isalpha(), isdigit()–
Used to check a character.
<stdlib.h>-Mainly used for data conversion
itoa() :
To convert a integer to
string. e.g. svar=itoa(ivar,10)
atof() :
Convert a string to float.
e.g. a=atof(b).
atoi() : Convert a
string to int. e.g. a=atoi(b).
<proccess.h>
exit() :Terminates
the current process.
Pointers :
Pointers are special type of
variables, which are concerned, with the memory address of other variables. The
use of pointers is much more frequent in C, than in any other languages and it
is use of pointers that has made c such a popular language. Pointers are used
to store the address of a memory variable and using this we can manipulate the
program to access memory address. Program that uses dynamic allocation cannot be
done without pointers.
int *p; // Indicates the
address stored in the variable 'p' is that of a int type variable.
char
*ch; // Indicates the address stored in the variable 'ch' is that of a char
type variable.
int i;
p=&i; // Thus another
variable can be used to store the address of the pointer variable 'j'. That
variable will thus hold the address of 'j' i.e. will be a pointer to another
pointer variable.
Pointer Arithmetic
A pointer to any variable type is an address in memory -- which is an integer
address. A pointer is definitely NOT an integer.
The reason we associate a
pointer to a data type is so that it knows how many bytes the data is stored in.
When we increment a pointer we increase the pointer by one block memory. So for
a character pointer ++ch_ptr adds 1 byte to the address. For an integer ++p adds
2 byte where ++p adds 4 bytes to the address for float.
Reference operator (&)
The address that locates a
variable within memory is what we call a reference to that variable. This
reference to a variable can be obtained by preceding the identifier of a
variable with an ampersand sign (&), known as reference operator, and which can
be literally translated as "address of". For example:
int n=10,*p;
p = &n;
This would assign to ‘p’ the
address of variable ‘n’, since when preceding the name of the variable ‘n’ with
the reference operator (&).
Dereference operator (*)
Using a pointer we can
directly access the value stored in the variable, which it points to. To do
this, we simply have to precede the pointer's identifier with an asterisk (*),
which acts as dereference operator and that can be literally translated to
"value pointed by".
int n,*p=10;
n = *p;
Arrays of Pointers :
Arrays of Pointers
are a data representation that will cope efficiently and conveniently with
variable length. To declare an array using dynamic allocation we need pointer
for the purpose
int *p,
n=10,i
p=(int
*)malloc(n*sizeof(int)); // converting the pointer to array
for(i=0;i<10;i++)
scanf(“%d”,&p[i]);
Dynamic Memory
allocation is a way to allocate memory blocks to a pointer and it can be done
while execution the program. malloc() and calloc() can be use for this purpose.
Since dynamic memory allocation uses library routines, it is not considered part
of the language.
malloc()
: malloc() allocates a block of size bytes from the memory heap. It allows a
program to allocate memory explicitly as it's needed, and in the exact amounts
needed. The heap is used for dynamic allocation of variable-sized blocks of
memory. Many data structures, such as trees and lists, naturally employ heap
memory allocation. All the space between the end of the data segment and the top
of the program stack is available for use in the small data models, except for a
small margin immediately before the top of the stack. This margin is intended to
allow the application some room to make the stack larger, in addition to a small
amount needed by DOS. In the large data models, all the space beyond the program
stack to the end of available memory is available for the heap.
Return Value:
On success, malloc returns a
pointer to the newly allocated block of memory.
On error (if not enough space
exists for the new block), malloc returns null. The contents of the block are
left unchanged.
If the argument size == 0,
malloc returns null.
calloc() - calloc
provides access to the C memory heap, which is available for dynamic allocation
of variable-sized blocks of memory. calloc allocates a block (nitems * size)
bytes and clears it to 0. To allocate a block larger than 64K, use farcalloc.
calloc allocates a block
(nitems * size) bytes and clears it to 0. To allocate a block larger than 64K,
use farcalloc.
There are two differences.
First, is in the number of arguments. Malloc() takes a single argument (memory
required in bytes), while calloc() needs two arguments (number of variables to
allocate memory, size in bytes of a single variable). Secondly, malloc() does
not initialize the memory allocated, while calloc() initializes the allocated
memory to ZERO.
Calloc(m, n)
is essentially equivalent to p = malloc(m*n); memset(p, 0, m*n); The zero fill
is all-bits-zero, and does not therefore guarantee useful null pointer values or
floating-point zero values. 'Free' is useable to release the memory allocated by
malloc or calloc.
Malloc(s),
returns a pointer for enough storage for an object of s bytes. Calloc(n,s);
returns a pointer for enough contiguous storage for n objects, each of s bytes.
The storage is all initialized to zeros.
Difference Between malloc() and calloc()
calloc
|
|
malloc
|
calloc() needs two
arguments (number of variables to allocate memory, size in bytes of a
single variable). calloc takes two arguments, and calculates their
product.
calloc() initializes
the allocated memory to ZERO.
Simply, where as,
Calloc(n,s); returns a pointer for enough contiguous storage for n
objects, each of s bytes. The storage is all initialized to zeros
p=(int *)calloc( 40, sizeof(int))
|
malloc takes a single
argument and allocates bytes of memory as per the argument taken during
its invocation.
Secondly, malloc()
does not initialize the memory allocated
Malloc(s); returns a
pointer for enough storage for an object of s bytes
p=(int *)malloc( 40* sizeof(int));
|
FILE
What are Files?
Output of the programs that
we had written are temporary so the results derived after running the programs
are lost after execution. C allows data to be stored permanently in a data file
with the help of an extensive set of library functions for handling these data
files. Using these library functions data can be stored in a secondary storage
device like a hard disk in the form of a data file, for later access.
Opening and Closing a Data file:
To store data in a file, the
data needs to be transferred from the computer's memory to the data file in the
storage media like the hard disk. However the data that is output does not go
directly to the disk when an output command is issued. Instead it goes to a
temporary storage area in memory called a buffer. Even if the buffer is not
full, the data in the buffer can be forcibly transferred to the file, if
required. How to do all these will be discussed later.
To access a data file, the
following steps need to be followed:
1.
Declaration of file
pointer: To
transfer data in and out of the buffer, a link needs to be first created between
the buffer and the operating system. When a program creates a file, it first
sets up a special structure in memory containing information that the computer
and the program need, to input or output information from the file. The
structure contains the address of the file's buffer, which tells the computer
where to find the information temporarily stored, to output to or input from the
disk and keeps track of the number of characters remaining in the buffer and the
position of the next character. This special structure data type is indicated
by the variable type FILE (all capital), already defined in the header file
"stdio.h". A pointer of the structure-data-type FILE is declared to finally
create the buffer area.
FILE *fp
- pointer variable fp of type FILE declared, to be used to indicate
beginning of the buffer.
2.
Opening the file:
The next step
after creating the file pointer is to open the data file. This is achieved by
associating or linking the file name of the data file with the buffer area, by
the help of the FILE type pointer fp, declared above. One more thing needs to
be indicated i.e. whether the data file should be opened as read-only,
write-only, or read-write both i.e. the mode of operation. The function that is
used to open a data file is fopen (). The general syntax for using the fopen ()
function is:
fp = fopen ("filename",
"mode");
The function fopen () returns
a pointer indicating the beginning of the buffer area associated with the file.
The filename and mode are strings that represent the name of the file and the
manner in which it should be opened. In case the file cannot be opened (due to
misspelled name or any other error), the function returns a NULL pointer.
Modes available for fopen()
File
Type
|
Description
|
Applicable To
|
"r"
|
Open
an existing file for reading only.
|
Existing file
|
"w"
|
Open
a new file for writing only. This will overwrite any existing file with
the same name.
|
New
file
|
"a"
|
Open
an existing file for appending (adding new information at the end of the
file). A new file gets created in case the file-name does not exist.
|
Existing/New
|
"r+"
|
Open
an existing file for reading and writing.
|
Existing file
|
"w+"
|
Open
a new file for reading and writing. This will overwrite any existing
file with the same name.
|
New
file
|
"a+"
|
Open
an existing file for reading and appending. A new file gets created in
case the file-name does not exist.
|
Existing/New
|
3.
Closing the file:
Finally, after
accessing the file it needs to be closed. Closing the file ensures that all
information in the file buffer is written to the file. If a file is not closed,
the end-of-file marker, indicating the end of a file, may not be properly
inserted also. Moreover, closing the file releases the file pointer, which can
be used for another file. A file is closed using the fclose () function as
shown below:
fclose (fp) ;