Escolar Documentos
Profissional Documentos
Cultura Documentos
Contents
1. C Fundamentals
1.1. C Characterset
1.2. Identifiers and Keywords
1.3. Variables
1.4. Literals
1.5. Data types
1.6. Where Variables are Declared
1.7. Scope and Life time of Variables
2. Operators
2.1. Introduction to Operators
2.2. Assignment Operator
2.3. Arithmetic Operators
2.4. Relational Operators
2.5. Arithmetic Assignment Operators
2.6. Increment and Decrement Operators
2.7. Logical Operators
2.8. Bitwise Operators
2.9. Pointer Operators
2.10. Conditional Operator
2.11. Precedence and associativity
3. Console I/O
3.1. Introduction to Files and Streams
3.2. Reading data from source
3.3. Writing data to sink
3.4. Standard Streams(stdin,stdout,stdprn)
3.5. Unformatted and formatted I/O Functions
4. Statements
4.1. Introduction
4.2. Selection Statements
4.2.1. If .....Else
4.2.2. If ladder
4.2.3. switch...case
4.3. Iteration statements
4.3.1. while Loop
4.3.2. do....while Loop
4.3.3. for Loop
4.4. Jump Statements
4.4.1. return
4.4.2. break
4.4.3. continue
5. Functions
5.1. Introduction
5.2. Function Declaration
5.3. Function Definition
2
C Programming SSIT
5.4. Function Call statement
5.5. Function Arguments
5.5.1. Call By Value and Call By Reference
5.6. Command Line Arguments
5.7. Recursive Function
6. Arrays and Strings
6.1. Introduction to Array
6.2. One Dimensional Array
6.3. Accessing Elements in Array
6.4. Passing Single Dimensional Array to Function
6.5. Strings
6.6. Two Dimensional Array
7. Pointers
7.1. Introduction to Pointers
7.2. Pointer Variables
7.3. The Pointer Operators
7.4. Pointer Arithmetic
7.5. Pointer Comparisons
7.6. Pointers and Arrays
7.7. Arrays of Pointers
7.8. Multiple Indirection
7.9. Pointer to Function
7.10. Cs Dynamic Memory Allocation Function
8. Structures, Union, Enumeration and typedef
8.1. Structures
8.2. Constructing Structure Object
8.3. Accessing Structure member
8.4. Structure Initialization
8.5. Arrays of Structure
8.6. Passing Structure to Function
8.7. Structure Pointer
8.8. Unions
8.9. Enumerations
8.10. Typedef
9. File I/O
3
C Programming SSIT
Overview of C
C seems a strange name for a programming language 'C' is one of the most
popular modern computer programming languages. The C language is developed in
1972 by Dennis M.Ritchie at Bell Laboratories (AT and T Bell Labs). The C language is
designed on BCPL (Basic combined programming language). The popularity of the C
language is due to its many characteristics.
Since it was developed along with the UNIX operating system it is strongly
associated with UNIX. This operating system was also developed at BELL laboratories
was coded almost entirely in C.
C FUNDAMENTALS
C Character set
4
C Programming SSIT
0-9 digits
Special Characters
+-*/=%&# !?^@`~\|
The length of these identifiers can vary from one to several characters.
Keywords
In All programming languages some words are reserved for some specific purpose. They are
playing key role to construct statements, hence they are called Keywords .In C89 ,32 words
are reserved and in C 99 ,37 words are reserved. They are
Variables
While solving a problem we may need to remember some data values temporarily. Such
values are placed in the named locations in the memory. These named locations in the memory are
called variables.
5
C Programming SSIT
To create a location in the memory, system needs three specifications
You create location or locations in the memory with these specifications, we can specify to
the system through variable declaration statement. Its syntax is:
type variablelist;
type variablename;
Variable name should be valid identifier.Remaing two specifications we are specifying through data
type.
Literals
Constants are also called literals or values. C' supports 4 types literals. They are
1. Character constant
Any single valid character is enclosed in between single quotation marks is called
character constant.
Ex: A, 0, 9, $, %'
2. String constant
Some thing which is placed in between double quotation marks is called string constant.
3. Numeric constant
Any particular sequence of 0 to 9 digits without any special character except a decimal point is
called numeric literal.
Data Types
char
If we want to hold a character literal temporarily, we need a variable of type char . To
declare a variable of char type, use keyword char
int
To store an integer constant we need a variable of type int
Ex: int n;
int variable takes two bytes memory in DOS operating system, four bytes in windows or unix.
float
To store real constant with less precision, we need a variable of type float
double
To store real constant with double precision, we need a variable of type double
7
C Programming SSIT
Ex. double basic;
void
If a function is not to accept any arguments, specify the same by using void.
returntype functionname(void);
Second use of void is to declare that function doesnt return any thing back to calling
function.
Preprocessor Directives
Global variables
Prototypes
/*statements*/
/*statements*/
/*statements*/
8
C Programming SSIT
}
Operators
int no;
no=10+20;
Here 10, 20 are operands and + is an operator. Depends upon number of operands the
operator is expecting all these operators are broadly categorized into following groups.
Depends upon type of operation operator is performing all these operators are broadly
categorized into following groups
1. Assignment operator =
9
C Programming SSIT
2.Arithmetic operator + * / %
8. Conditional operator ? :
11.Comma Operator ,
Assignment Operator
Syntax
Variable=value|expression;
Example
int no;
no=35;
no=10+28;
Multiple Assignments
int a, b, c, d, e;
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same ways that are used
in algebra.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% modulus
Relational Operators
< Less Than, > Greater than , >= Greater Than Equal To, <= Less Than Equal To
The out come of relational expression always either 1 or 0.If relationship exists 1 otherwise
0.
Example:
14>8 (evaluated to 1)
34<=19 (evaluated to 0)
11
C Programming SSIT
a=a+4;
a=a-4;
a=a*4;
a=a/4;
a=a%4;
Variable operator=value;
a+=4;
a-=4;
a*=4;
a/=4;
a%=4;
and
Both are unary operators. They expect numeric type variable as an operand
Example:
i++;
J--;
12
C Programming SSIT
These operators can precede the operand or can follow the operand
or
There is no deference between prefix form and postfix form in short expressions. But there
is a difference in long expressions.
int i=10, j;
j=++i;
In prefix form it fix the operation first and then uses the operand in that context.In this
example i will be incremented by 1 and i will be assigned to j.
j=i++;
In postfix form, operand value will be used in the context and performs operation. In this i
will be assigned to j first and i will be incremented by 1.
Logical Operators
Logical not !
1 1 1
1 0 0
0 1 0
0 0 0
13
C Programming SSIT
The truth table for || operator
1 1 1
1 0 0
0 1 0
0 0 0
In and and or operation if left operand determines the answer right operand will not be
evaluated.
Logical not (!) is a unary operator .Syntax to construct an expression using logical not is
!(expression)
!(5>6) is evaluated to 1
!(6>5) is evaluated to 0
Bitwise Operators
The bitwise operators provided by C may only be applied to operands of type char, short, int
and long.
| Bitwise inclusive OR
^ Bitwise exclusive OR
~ Ones complement(NOT)
type * variablename;
Ex: int * p;
Pointer Operators
The & is a unary operator that returns the memory address of its operand.
Example:
int count,*m;
m=&count;
The first statement will create one integer variable with name count and an integer pointer with
name m.
The second statement places address of count variable into the pointer variable m.
You can think of & has returning the address of. Therefore the preceding statement can be
verbalized as m receives the address of count".
To understand the above assignment better, assume that the variable count uses memory location
2000 to store its value, also assume that count has value of 100, then after preceding assignment
m will have the value 2000.
2. *( At address):
The second pointer operator is the compliment of & ,This is also a unary operator that returns the
value located at that address.
That follows
Example:
q=*m;
Places the value of count into q . Thus q will have the value 100, 100 is actually stored in the
memory address 2000, which is address that was stored in m.so you can think of * as at
15
C Programming SSIT
address. In this case the preceding statement can be verbalized as q receives the value at
address m".
Conditional Operator
The conditional expressions written with the ternary operator "?:" provides an alternate way
to write the if conditional construct. This operator takes three arguments.
Expression1? Expression2:Expression3
If expression1 is true (i.e. value is non-zero) then the value returned would be expression2
otherwise the value returned would be expression3.
sizeof is a unary compile-time operator that returns the length, in bytes, of the variable or
parenthesized type specifier that it precedes. For example, assuming that integers 4 bytes and
doubles are 8 bytes, this fragment will display 8 4.
double f;
Remember, to compute the size of a type, you must enclose the type name in parentheses.
This is not necessary for variable names, although there is no harm done.
In case of a tie between operations of same priority then they are evaluated based on their
associativity. You can use parenthesis to change the order of evaluated. If there is more than one
set of parenthesis the innermost parenthesis will be performed first followed by the operations with
in the second innermost pair and so on?
Operator Associativity
16
C Programming SSIT
^ left to right
| left to right
|| left to right
?: right to left
Casts
You can force an expression to be of a specific type by using a cast. The general form of a cast is
(type) expression
Where type is a valid data type. For example, to cause the expression x/2 to evaluate to type float,
write
(float)x/2
17
C Programming SSIT
EXERCISE-1
a) 5 b) 4 c) 6 d) 7
a) 1 b) 4 c) 3 d) 2
7) x%y is equal to
a)(x-(x/y)) b)(x-(x/y)*y)
c)(y-(x/y)) d)(y-(x/y)*y)
18
C Programming SSIT
8) The operator can be applied to
10) If both the operands of the operator are integers the result is
c) Option a or b d) undefined
c) Float value
d) Syntax error
12) Assume c1 and c2 as char variables if C1='A'; C2='2'; what are the
results of the statements putchar (C1+3) and putchar ((2-1);)
a)! b)! = c) ~ d) ==
19
C Programming SSIT
18) Identify the relational operator
EXERCISE-2
a) ^ b) ~ c) & d)1
a) & b) ^ c) ~ d) 1
17. Which expression yields correct value for the expression 1/3?
Console I/O
In C any physical device which is used to do input or output operations is called file.
Examples: Keyboard, Screen, Printer, Disk file, etc...
Stream
A stream is a logical device, which is an abstraction between the physical device and program.
Via stream only input output operations takes place. There are two types of streams.
Text Stream
Binary Stream
From source we read data, to sink we write data. To read data from source do the following.
3. Read data from stream ,in turn it read it from associated source
Standard Streams
To read data from user via keyboard or to give output to the user via screen we need not do
first two steps in reading and writing because when C program execution is started some predefined
streams are opened automatically. They are
22
C Programming SSIT
stdout : A text stream opened in append mode and associated to screen.
So to read data from user, we have to read from stdin, where as to give out put to the user write
data to stdout.To read data from stdin to write data to stdout we have built-in functions.
1. getchar()
Syntax:
#include<stdio.h>
int getchar( void );
The getchar() function returns the next character from STDIN, or EOF if the end of file is reached.
2. getch()
Syntax:
#include <conio.h>
int getch( void );
The getch() function returns the next character from STDIN, or EOF if the end of file is reached.
3. getche()
Syntax:
#include <conio.h>
int getche( void );
The getche() function returns the next character from STDIN, or EOF if the end of file is reached.
4. gets()
Syntax:
#include <stdio.h>
char *gets( char *str );
The gets() function reads characters from STDIN and loads them into str, until a newline or EOF is
reached. The newline character is translated into a null termination. The return value of gets() is
the read-in string, or NULL if there is an error.
23
C Programming SSIT
5. scanf()
Syntax:
#include <stdio.h>
int scanf( const char *format, ... );
The scanf() function reads input from stdin, according to the given format, and stores the data in
the other arguments. It works a lot like printf(). The format string consists of control characters,
whitespace characters, and non-whitespace characters. The control characters are preceded by a %
sign, and are as follows:
To write data to stdout we have putchar (), puts (),printf() built-in functions.
1. putchar ()
Syntax:
#include <stdio.h>
int putchar( int ch );
putchar( ch );
2. puts()
Syntax:
#include <stdio.h>
int puts( char *str );
24
C Programming SSIT
The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on
failure
3. printf ()
Syntax:
#include <stdio.h>
int printf( const char *format, ... );
The printf() function prints output to STDOUT, according to format and other arguments passed to
printf(). The string format consists of two types of items - characters that will be printed to the
screen, and format commands that define how the other arguments to printf() are displayed.
Basically, you specify a format string that has text in it, as well as "special" characters that map to
the other arguments of printf(). For example, this code
The %s means, "insert the first argument, a string, right here." The %d indicates that the second
argument (an integer) should be placed there. There are different %-codes for different variable
types, as well as options to limit the length of the variables and whatnot.
Code Format
%c Character
%d signed integers
%i signed integers
%e scientific notation, with a lowercase "e"
%E scientific notation, with a uppercase "E"
%f floating point
%g use %e or %f, whichever is shorter
%G use %E or %f, whichever is shorter
%o Octal
%s a string of characters
%u unsigned integer
%x unsigned hexadecimal, with lowercase letters
%X unsigned hexadecimal, with uppercase letters
%p a pointer
the argument shall be a pointer to an integer
%n into which is placed the number of characters
written so far
25
C Programming SSIT
%% a '%' sign
Statements
You do this, we can specify to the system by using statement. A statement is a complete instruction
categorizes statements into these groups:
Selection
Iteration
Jump
Label
Expression
Block
26
C Programming SSIT
1. Selection Statements
C supports two selection statements: if and switch. In addition, the (? :) operator is an alternative
to if in certain circumstances.
If
If(expression)statement;
[else statement;]
Where a statement may consist of a single statement, a block of statements, or nothing. The else
clause is optional.
27
C Programming SSIT
If Ladder
If we have several groups of statements and one of the group is to be executed selectively
specify that intension by using if Ladder or switch in some cases.
Syntax
if(expression)
statement;
else if(expression)
statement;
else if(expression)
statement;
.
.
.
else statement;
switch
C has a built-in multiple-branch selection statement, called switch, which successively
test the value of an expression against list of integer or character constant. When a match is
found, the statements associated with that constants are executed. The general form of switch
statement is
switch(expression){
case constant1:
statement sequence
[break];
case constant2:
statement sequence
[break];
case constant3:
statement sequence
[break];
.
.
28
C Programming SSIT
default: statement sequence;
}
The expression must be evaluated to an integer type thus we can use character or integer
values, but floating point expressions, for example, are not allowed.
The value of the expression is tested against the values, one after another, of the constants
specified in the case statements. When a match is found, the statement sequence associated
with that case is executed until the break statement or the end of the switch statement is
reached. The default statement is executed if no matches are found. The default is optional,
and if it is not present, no action takes place if all matches fail.
There are the three important things to know about the switch statement:
The switch differs from the if in that switch can only in equality, where as if can
evaluate any type of relational or logical expression.
No two case constants in the same switch can have identical values. If character
constants are used in the switch statement, they are automatically converted to
integers.
Iteration statements
You do these things repeatedly, we can specify to the system by using one of the three
repetition statements:
1. while loop
2. do-while loop
3. for loop
while(condition)
statement;
29
C Programming SSIT
The general form of the do-while loop is
do
{
Statement;
}while(condition);
The do-while loop iterates until condition becomes false. The do-while loop checks its condition
at the bottom of the loop. This means that the do-while always executes at least once.
You do this things repeatedly varying so and so variable value from so and so to so with
increment or decrement so and so to specify use for statement.
for(Initialization;Condition;Increment)
{
//statements
}
int no;
for(no=1;no<=15;no++)
{
printf(%d ,no);
}
Jump Statements
30
C Programming SSIT
C has four statements that perform an unconditional branch:
1. return
2. goto
3. break
4. continue
You can use return and goto anywhere inside the function. You can use break and
continue statements inside nay of the loop statements. You can also use break with switch.
You return this value back to the calling area we can specify to the system by using
return statement.
return value|expression;
To ask the system to bring the control out of void method use return statement.
return value|expression;
break;
General form
continue;
int i;
{
31
C Programming SSIT
printf(%d ,i);
printf(\n);
Introduction to Functions
Introduction
Preprocessor Directives
Global variables
Prototypes
int main(parameter list){
/*statements*/
}
Generally in C, what are the functions we are writing other than main() function we declare them
before the main(), we call them in main() and define them after main(). So function contains
declaration and definition.
Function Declaration
32
C Programming SSIT
Function declaration syntax:
To write a function declaration easily tries to get answers for the following questions
Function Definition
Syntax.
/*statements*/
Example:
if(a>b)return a;
else return b;
You run so and so function we can specify to the system by using function call statement. Syntax
Functionname(arguments)
To ask the system to run a function called max() which is expecting two integers
max(10,20);
33
C Programming SSIT
when this statement is executed control goes to max() function taking arguments to the formal
parameters and function executes, when function returns ,return value (if any)replaces the function
call statement. To receive the return value use the following syntax.
Variable=functionname(arguments);
Function Arguments
If function has to accept arguments it must declare the parameters that will receive the
values of the arguments, has shown in the following function the parameter declaration occur after
the function name.
if(a>b)
return a;
else
return b;
}
In a computer language there are two ways to pass the arguments to a subroutine , The
first is call by value. This method copies the value of the argument into the formal parameter of the
function. In this case , changes made to the parameter have no effect on the argument.
Call by reference is second way of passing the arguments to the function. In this method the
address of the argument will be copied to the formal parameters. In side the sub routine the
address is used to access the actual argument used in the call. This means that the changes made
to the parameter effect to the argument.
Example:
#include<stdio.h>
void swap(int *,int *);
int main(void)
{
int i,j;
i=10;
j=20;
printf(I and J before swapping : %d %d\n,i,j);
swap(&I,&j); /* pass the addresses I and j */
printf(I and j after swapping : %d %d\n,i,j);
return 0;
}
void swap(int *x,int *y)
{
int temp;
34
C Programming SSIT
temp=*x; /* save the value at address x */
*x=*y; /* put y in to x */
*y=temp; /* put x into y */
}
is called command line. Through command line we are giving instruction to operating
system to run a program. Here copy is the command (name of the program), temp.txt
temp1.txt are the command line arguments. Operating system is making call to the main
function of copy program by passing two arguments.
To receive first argument define parameter of int type because first argument is integer
type, in above example first argument is 3.Define un sized char pointer array to receive second
argument. So main function definition should look like this:
Where argc is argument count, argv is argument values. If argc receives 0 means no
command line arguments are specified by the user. argv[0] points the command, argv[1]
first command line argument, so on.
Recursive Functions
Recursion is a programming technique that allows the programmer to express operations in terms
of themselves. A useful way to think of recursive functions is to imagine them as a process being
performed where one of the instructions is to "repeat the process". This makes it sound very similar
to a loop because it repeats the same code, and in some ways it is similar to looping.
On the other hand, recursion makes it easier to express ideas in which the result of the recursive
call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes
be completed without the recursive call.
35
C Programming SSIT
One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot
high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks.
syntax:
void recurs()
{
recurs(); /* Function calls itself */
}
int main()
{
recurs(); /* Sets off the recursion */
return 0;
}
An Array is a group of similar type of variables. We can construct array of any type like int,
float, char, double. Moreover we can construct one dimensional array as well as multidimensional
array.
Array declaration:
To construct a one dimensional array system requires the following 3 specifications, they include.
Syntax
Type ArrayVariableName[size];
36
C Programming SSIT
int nos[5];
if above statement is executed for all 5 variables memory locations will be allocated in a continues
manner.
The amount of storage required to hold an array is directly related to its type and size, for a single
dimensional array the total size in bytes will be computed as
Variables in an array are called elements. Each element is identifying with unique index
value. Indexing is zero based. First element index is 0, second element index is 1,so on. To name
the element of the array syntax is
Arrayname[index]
While constructing the array, if we know what values elements are to represent, use the following
syntax.
int nos[]={10,20,30,40,50} ;
In C , you can not pass an entire array as an argument to function, You can however pass a
pointer to an array by specifying arrays name with out an index. For example the following program
fragment passes the address of nos to display().
int main(void)
{
int nos[]={10,20,30,40,50};
display(nos);
return 0;
}
If a function receives a pointer to a one dimensional array, you can declare its formal
parameter in one of three ways: as a pointer, as a sized array or as un sized array. For example, to
receive nos, functions called display() it can be declared as
Example:
37
C Programming SSIT
{
int i;
for(i=0;i<5;i++)
{
printf(%d ,*(p+i));
}
}
Or
Or
void display(int p[]) /* Unsized array */
{
int i;
for(i=0;i<5;i++)
{
printf(%d ,p[i]);
}
}
All three declaration methods produce similar results because each tells the compiler that an
integer pointer is going to be received
Strings
Some thing which is placed in between double quotation marks is called string literal .In C a
string is treated as one dimensional char array terminated with null character. This means that after
the last truly usable char there is a null, hex 00, which is represented in C by '\0'. The subscripts
used for the array start with zero (0). The following line declares a char array called str. C provides
fifteen consecutive bytes of memory. N.B. Only the first fourteen bytes are usable for character
storage, because one must be used for the string-terminating null.
char str[15];
The following is a representation of what would be in RAM, if the string "Hello, world!" is
stored in this array.
Characters: H e l l o , w o r l d !
Hex values: 48 65 6C 6C 6F 2C 20 77 6F 71 6C 64 21 00
Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
38
C Programming SSIT
The array name always contains the first element address. Thus, both of the following will
save the address of the 0th character in the pointer variable ptr.
ptr = str;
ptr = &str[0];
String Functions
The string functions operate on null-terminated arrays of characters and require the
header<string.h>
1. strlen()
Syntax:
#include <string.h>
size_t strlen( char *str );
The strlen() function returns the length of str (determined by the number of characters
before null termination).
The following code will result in len having the value 13.
2. strcpy()
Syntax:
#include <string.h>
char *strcpy( char *to, const char *from );
The strcpy() function copies characters in the string from to the string to, including the null
termination. The return value is to.
char S[25];
char D[25];
strcpy(D, &S[8]);
Note. If you fail to ensure that the source string is null-terminated, very strange and sometimes
very ugly things may result.
3. strncpy()
Syntax:
#include <string.h>
char *strncpy( char *to, const char *from, size_t count );
The strncpy() function copies at most count characters of from to the string to. If from has
less than count characters, the remainder is padded with '\0' characters. The return value is the
resulting string.
4. strcat()
Syntax:
#include <string.h>
char *strcat( char *str1, const char *str2 );
The strcat() function concatenates str2 onto the end of str1, and returns str1. For example:
5. strncat()
Syntax:
#include <string.h>
char *strncat( char *str1, const char *str2, size_t count );
The function strncat() concatenates at most count characters of str2 onto str1, adding a null
termination. The resulting string is returned.
Given the following declarations, several things are possible, but only one is commonly
used.
Concatenating five characters from the beginning of S onto the end of D and placing a null
at the end:
40
C Programming SSIT
strncat(D, S, 5);
strncat(D, S, strlen(S) -1);
Note: If you fail to ensure that the source string is null-terminated, very strange and
sometimes very ugly things may result.
6. strcmp()
Syntax:
#include <string.h>
int strcmp( const char *str1, const char *str2 );
For example:
7. strncmp()
Syntax:
#include <string.h>
int strncmp( const char *str1, const char *str2, size_t count );
The strncmp() function compares at most count characters of str1 and str2. The return
value is as follows:
If there are less than count characters in either string, then the comparison will stop after
the first null termination is encountered.
41
C Programming SSIT
Two-Dimesional Array
C supports multi dimensional arrays . The simplest form of multidimensional array is the two
dimensional array. A two dimensional array is essentially , an array of one dimensional arrays.
type arrayvariablename[size][size];
Example:
int twod[4][3];
arrayname[rowindex][columnindex];
twod[0][0]=1;
In case of two dimensional array , the following formula yields the number of bytes of memory
needed to hold it.
Pointers
A pointer is a variable that holds memory address. This address is the location of another variable
in memory.
Correct understanding and use of pointers is crucial to successful c programming, there are several
reasons for this:
2. Pointers provide the means by which function can modify their calling arguments.
3. Pointers support dynamic allocation and dynamic data structures such as binary trees and linked
lists
Pointer variables
42
C Programming SSIT
A pointer is a variable that holds a memory address. A variable is going to be a pointer, it must be
declared as such
type * variablename;
Example: int * p;
The & is a unary operator that returns the memory address of its operand.
Example:
int count,*m;
m=&count;
The first statement will create one integer variable with name count and an integer pointer with
name m.
The second statement places address of count variable into the pointer variable m.
You can think of & has returning the address of. Therefore the preceding statement can be
verbalized as m receives the address of count".
To understand the above assignment better, assume that the variable count uses memory location
2000 to store its value, also assume that count has value of 100, then after preceding assignment
m will have the value 2000.
2. * at address:
The second pointer operator is the compliment of & ,This is also a unary operator that returns the
value located at that address.
That follows
Example:
q=*m;
Places the value of count into q . Thus q will have the value 100, 100 is actually stored in
the memory address 2000, which is address that was stored in m.so you can think of * as at
43
C Programming SSIT
address. In this case the preceding statement can be verbalized as q receives the value at
address m".
Pointer Arithmetic
There are only two arithmetic operations that can use on pointers, they include..
1. Addition
2. Subtraction
Let p1 be an integer pointer with the address 2000. Also assume ints are 2 bytes long. After the
expression
P1++;
P1 contains 2002, not 2001. The reason for this is that each time p1 is incremented it will point to
the next integer. The same is true for decrements.
Each time a pointer is incremented , it points to the memory location of the next element of its base
type. Each time it is decremented it points to the memory location of the previous element.
For Example you may add or subtract integers to or pointers. The expression
p1=p1+12;
Makes p1 point to the 12th element of p1 type beyond the one it currently points to.
Beside addition and subtraction of a pointer and an integer, only one other arithmetic
operation is allowed: You can subtract one pointer to another in order to find the number of objects
base type that separates the two. All other arithmetic operations are prohibited. Specifically you
cant multiply or divide pointer, you cant add two pointers, you cant apply the bitwise operators to
them, you cant add or subtract float or double from pointer.
i.e.
Subtracting one pointer from other, in order to find number of objects of base type that
separate the two pointers.
we are already familiar with arrays(collection of similar data elements reffered through common
name).
44
C Programming SSIT
Processing array with pointers is much more effective and it is very simple, bcz generally all data
elements of an array are stored in continuous memory locations, so if you know address of starting
element of an array, it is very easy to move till the end.
To know the address of any variable we will simply prefix & to that variable
Array_name[index];
let us consider
p=&a[0];
Once u know address of first element its very easy to move forward, thru pointer addition.
At the same time we can move from last element to first also, thru pointer subtraction from last
element address.
Example:
The base address value is obtained by mentioning its name first value can be accessed by
using *p .similarly we can access second element *(p + i).
Cs Memory Map
A complied C program creates and uses four logically distinct regions of memory. The first
region is the memory that actually holds the programs executable code. The next region of the
memory where global variables are stored. The remaining two regions are stack and the heap. The
stack is used for a great many things while program executes. It holds the return addresses of
45
C Programming SSIT
functions call, arguments to functions and local variables. It will also save current state of the CPU.
The heap is a region of free memory that your program can use via Cs dynamic memory allocation
functions.
Standard C defines four dynamic allocation function that all compiler will supply:
calloc(),malloc(),free(),realloc()
1. calloc()
Syntax:
#include <stdlib.h>
void *calloc( size_t num, size_t size );
The calloc() function returns a pointer to space for an array of num objects, each of size size.
calloc() returns NULL if there is an error.
2. malloc ()
Syntax:
#include<stdlib.h>
void *malloc( size_t size );
The function malloc() returns a pointer to a chunk of memory of size size, or NULL if there is an
error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you
are done with it.
3. realloc ()
Syntax:
#include <stdlib.h>
void *realloc( void *ptr, size_t size );
The realloc() function changes the size of the object pointed to by ptr to the given size. size can by
any size, larger or smaller than the original. The return value is a pointer to the new space, or NULL
if there is an error.
4. free ()
Syntax:
#include <stdlib.h>
void free( void *ptr);
46
C Programming SSIT
The free() function deallocates 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().
Structures
Structures
Union
Typedef
Bit-field
47
C Programming SSIT
Enumeration
Structures
Need of structure
How will you store the address of a person which consists of name, street, city, state, pin
with the following types
char name[20]
char street[20]
char city[20]
char state[3]
unsigned long int pin
The above stated address will be created in 5 locations which may not be side-by-side
to store all the variables of a particular data in consecutive locations of memory there is a need for
new data type.
i.e., STRUCTURE
Structure Features
struct tag{
type member-name;
type member-name;
type member-name;
.
.
} structure-variables;
Structure Examples:
struct Addr
{
char name[20];
char street[20;
48
C Programming SSIT
char city[20];
char state[3];
unsigned long int pin;
};
Department Details
struct dept
{
int deptno;
char name[20];
char location[20];
};
Book details
struct book
{
char bname[20];
float cost;
int copies;
};
Circle structure
struct circle
{
int x;
int y;
int radius;
};
Box Details
struct Box
{
double width;
double height;
double depth;
};
We have created
49
C Programming SSIT
A simple variable
A pointer variable
A simple array variable
An array of pointers
Example:
int no;
int *p;
char name[20];
int *p[10];
When above statement is executed for all members memory locations are allocated as per
their specifications in a continuous manner.
Example:
Individual members of a structure are accessed through the use of the . (dot) Operator.
For Example, the following statement assigns the pin code 500036 to the pin field of the structure
variable addr_info.
addr_info.pin=500036;
The general form for accessing the member of the structure is objectname.membername
Examples:
50
C Programming SSIT
addr_info.name
addr_info.street
addr_info.city
addr_info.state
addr_info.pin
comp.deptno
comp.name
comp.loc
b.width
b.height
b.depth
Structure initialization
struct box
{
double width;
double height;
double depth;
}b={25,40,55};
struct addr
{
char name[20];
char street[20};
char city[20];
char state[3];
unsigned long int pin;
}addr_info={sai, patamata, vja, ap ,34567} ;
51
C Programming SSIT
Write a program to accept and display the address details
#include<stdio.h>
#include<conio.h>
int main(void)
struct addr
{
char name[20];
char street[20];
char city[25];
char state[3];
unsigned long pin ;
};
struct addr addr_info;
int main(void)
{
clrscr();
printf(Enter Name);
gets(addr_info.name);
printf(Enter Street);
gets(addr_info.street);
printf(Enter City);
gets(addr_info.city);
printf(Enter State);
gets(addr_info.state);
printf(Enter Pin);
scanf(%d,addr_info.pin);
clrscr();
printf(Name:%s\n,addr_info.name);
printf(street:%s\n,addr_info.street);
printf(city:%s\n,addr_info.city);
printf(state:%s\n,addr_info.state);
printf(pin:%d\n,addr_info.pin);
}
Array of structures
As we know array is collection of similar data types like int, float, char etc. In the same
way we can also define array of structures. In that array every element is of structure type.
Array of structures can be declared as follows.
struct addr
{
char name[20];
char street[20];
char city[25];
char state[3];
unsigned long pin ;
}; struct addr addr_info[5];
52
C Programming SSIT
We can take any data type for declaring structure members like int, float, char etc.we can also
take objects of one structure as members of another structure.
struct date
{
int dd;
int mm;
int yy;
};
struct person
{
char name[25];
struct date dob;
}emp;
Like variables of standard type structure variables can also be passed to the function by
value or address .
Syntax:
Example:
Pointer to a STRUCTURE
Pointer is a variable that holds the address of another variable. The variable may be of any
type int, float, char etc. in the same way we can define a pointer to a structure. Structure pointers
are declared by placing * in front of structure variables name.
Example:
struct addr
{
char name[20];
char street[20];
char city[25];
char state[3];
unsigned long pin ;
53
C Programming SSIT
};
struct addr *p;
p is pointer to structure.
To access the members of the structure using a pointer to that structure you must use the -
> operator.
Example:
p->name;
p->street;
p->city;
p->state;
p->pin;
p->pin=500036;
54
C Programming SSIT
Enumerations
Enumeration is a set of named integer constants. Enumerations are defined much like
structures. The keyword enum the start of the enumeration type. The general form for
enumerations is
Syntax
enum tag
{
//Enumeration list
} var_list;
enum coin
{
penny, nickel, dime, quarter, half_dollar, dollar
};
The enumeration tagname can be used to declare variables of its type the following declares
money to be a variable of type coin:
money=dime;
if(money==quarter)
printf(Money is a quarter.\n);
The key point to understand about is the enumeration is that each of the symbols stands for an
integer value. Each symbol is given a value one greater than the symbol that preceeds it.The value
of the first enumeration symbol is zero. Therefore,
printf(%d %d ,penny,dime);
55
C Programming SSIT
Introduction to Preprocessor
Preprocessing
#include
#include <filename>
Searches standard library for file
Use for standard library files
#include "filename"
Used for:
Programs with multiple source files to be compiled together
Symbolic Constants:
#define Preprocessor directive used to create symbolic constants and macros Symbolic
constants
When program compiled, all occurrences of symbolic constant replaced with replacement text
56
C Programming SSIT
Format #define identifier replacement-text
Example:
#define PI = 3.14159
Replaces PI with " = 3.14159 " Cannot redefine symbolic constants once they have been
created
Macros
area = CIRCLE_AREA( c + 2 );
Multiple arguments
57