Sie sind auf Seite 1von 113

C Programming

Language
Table of Contents :
 BASIC STEPS OF C PROGRAMMING LANGUAGE
 STATEMENTS AND LOOPS.
 FUNCTIONS, STRINGS AND ARRAYS
 POINTERS AND DYNAMIC MEMORY ALLOCATION
 STRUCTURE AND UNION
CHAPTER - 1
 INTRODUCTION TO C-LANGUAGE
 GETTING TO KNOW THE C COMPILER
 WHERE C-LANGUAGE IS USED
 WHY WE LEARN C-LANGUAGE
 COMPILATION AND EXECUTION OF C PROGRAM
 THE BASIC STRUCTURE OF A C PROGRAM
 TOKENS
 PREPROCESSOR
 INPUT/OUTPUT FUNCTION
 OPERATOR
 PRIMITIVE DATA TYPES
Introduction to C- Language

C IS A GENERAL-PURPOSE HIGH LEVEL LANGUAGE THAT WAS


ORIGINALLY DEVELOPED BY DENNIS RITCHIE, KEN THOMPSON, BRIAN
KERNIGHAN AT AT&T BELL LABS FOR THE UNIX OPERATING SYSTEM.
C HAS NOW BECOME A WIDELY USED PROFESSIONAL LANGUAGE FOR
VARIOUS REASONS.

 EASY TO LEARN
 STRUCTURED LANGUAGE
 IT PRODUCES EFFICIENT PROGRAMS
 IT CAN HANDLE LOW-LEVEL ACTIVITIES
 IT CAN BE COMPILED ON A VARIETY OF COMPUTERS
Uses of C Language:
SOME EXAMPLES OF THE USE OF C MIGHT BE:
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Data Bases
 Language Interpreters
 Utilities
Execution of C program

• A C PROGRAM USES ENGLISH WORDS FOR WRITING THE


PROGRAM.
• THE CODING IS WRITTEN IN A FILE WITH THE EXTENSION C.
• EXECUTION OF C PROGRAM OCCURS IN 4 PHASES.
 Writing code
 Compiling of code
 Linking
 Execution
Execution of C program ( cont.. )

Interpreter

Instruction of source

Next line phase Interpreter

Executable code
Execution of C program ( cont.. )

Compiler and Assembler

Source Compiler/ Object


code Assembler code
The Basic Structure of C-program
/* C Basics example Program */
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf("Hello World! \n");
return 0;
}
Steps to compile and execute C program

1. TYPES THE C PROGRAM IN TURBO C COMPILER SAVES AS


“NAME.C”.
2. TO COMPILE THE C PROGRAM PRESS ALT+F9.
3. IF THERE IS NO ERROR IN C PROGRAM EXECUTABLE FILE WILL BE
GENERATED IN THE NAME NAME.EXE.
4. TO RUN THIS EXECUTABLE FILE BY PRESSING CTRL+F9.
5. YOU WILL SEE THE OUTPUT ON THE BLACK SCREEN OR CONSOLE
SCREEN.
Tokens:

 THE KEYWORDS, IDENTIFIERS, CONSTANTS, STRING LITERALS,


AND OPERATORS DESCRIBED IN THIS SECTION ARE EXAMPLES
OF TOKENS.
 PUNCTUATION CHARACTERS SUCH AS BRACKETS ([ ]), BRACES ({
}), PARENTHESES ( ( ) ), AND COMMAS (,) ARE ALSO TOKENS.
Identifiers:

 IDENTIFIERS ARE THE NAMES GIVEN TO PROGRAM ELEMENTS


SUCH AS VARIABLES, FUNCTIONS AND ARRAYS ETC.
 IDENTIFIERS ARE ALSO THE NAMES OF THE OBJECTS, WHICH CAN
TAKE DIFFERENT VALUES BUT ONLY ONE VALUE AT A TIME.
 ALLOWABLE CHARACTERS IN IDENTIFIERS ARE THE LETTERS
FROM A TO Z, A TO Z, THE DIGITS FROM 0 TO 9 , AND UNDERSCORE
CHARACTERS (_). BUT THE IDENTIFIERS MUST BEGIN WITH A
LETTER OR AN UNDERSCORE (_) NOT BEGIN WITH NUMBERS.
 FOR EXAMPLE, NAME, ROHIT_MITTAL, MARKS ETC. ARE SOME
VALID IDENTIFIERS.
Keywords:

 AT THE TIME OF DESIGNING COMPILER OF A PROGRAMMING


LANGUAGE SUCH AS C, SOME WORDS ARE RESERVED TO SPECIFIC
TASKS.
 SUCH WORDS ARE CALLED KEYWORDS OR RESERVED WORDS.
 THE KEYWORDS CANNOT BE USED AS VARIABLE NAMES.
 THERE ARE 32 KEYWORDS AVAILABLE IN C.

auto double int struct break else long switch

case enum register typedef char extern return union

const float short unsigned continue for signed void

default goto sizeof volatile do if static while


Variables:

 A VARIABLE IS A NAME THAT C LANGUAGE COMPILER ASSOCIATES


WITH A STORAGE LOCATION IN THE MAIN MEMORY OF THE
COMPUTER.
 VARIABLE HOLD DATA THAT CAN BE MODIFIED DURING PROGRAM
EXECUTION.
 AFTER YOU DECLARE A VARIABLE IN A PROGRAM, YOU CAN
ASSIGN IT A VALUE.
Rules to declare a Variable:
 VARIABLE CAN CONSIST OF ANY SEQUENCE OF LETTERS, DIGITS
AND UNDERSCORES (_).
 NO OTHER SPECIAL CHARACTERS SUCH AS +, $, -, ETC. ARE
ALLOWED, WHILE GIVING A NAME TO A VARIABLE.
 THE FIRST CHARACTER OF A VARIABLE SHOULD BE A LETTER OR
AN UNDERSCORE (_).
 IT CAN BE FOLLOWED BY LETTERS, DIGITS, OR UNDERSCORE.
 VARIABLES NAMES ARE CASE SENSITIVE, THAT IS, NUM, NUM, AND
NUM ARE THREE DIFFERENT VARIABLES.
 THOUGH UPPERCASE LETTERS ARE ALLOWED, USUALLY
VARIABLES IN C LANGUAGE ARE WRITTEN IN LOWERCASE.
 RESERVED WORDS CALLED KEYWORDS WHICH CONVEY SPECIFIC
MEANING TO THE COMPILER OF C LANGUAGE CANNOT BE USED
AS NAMES OF IDENTIFIERS OR VARIABLES.
Constant:
 IN A PROGRAM, A NAME MAY BE ASSIGNED TO A DATA ITEM. IF IT
REMAINS THE SAME, THROUGHOUT THE PROGRAM EXECUTION,
THEN WE SAY THAT THE VALUE OF NAME IS A CONSTANT.
 THUS, CONSTANT IS A VALUE, WRITTEN INTO A PROGRAM
INSTRUCTION THAT DOES NOT CHANGE DURING THE EXECUTION
OF A PROGRAM.
 THERE ARE THREE TYPES OF CONSTANTS:
 String constant
 Numeric constant
 Character constant
Preprocessor :
 THE C PREPROCESSOR IS A MACRO PROCESSOR THAT IS USED
AUTOMATICALLY BY THE C COMPILER TO TRANSFORM YOUR
PROGRAM BEFORE ACTUAL COMPILATION.
 IT IS CALLED A MACRO PROCESSOR BECAUSE IT ALLOWS YOU TO
DEFINE MACROS, WHICH ARE BRIEF ABBREVIATIONS FOR LONGER
CONSTRUCTS.
 ALL PREPROCESSOR COMMANDS BEGIN WITH A POUND SYMBOL
(#).
 IT MUST BE THE FIRST NONBLANK CHARACTER, AND FOR
READABILITY, A PREPROCESSOR DIRECTIVE SHOULD BEGIN IN
FIRST COLUMN.
Preprocessor ( cont.. ) :
 FOLLOWING SECTION LISTS DOWN ALL IMPORTANT
PREPROCESSOR DIRECTIVES:

Directive Description
#define Substitutes a preprocessor macro

#include Inserts a particular header from another file

#undef Undefines a preprocessor macro

#ifdef Returns true if this macro is defined

#ifndef Returns true if this macro is not defined

#if Tests if a compile time condition is true

#else The alternative for #if

#pragma Issues special commands to the compiler, using a standardized method


Basic Input/output Function:
 THERE ARE MANY LIBRARY FUNCTIONS AVAILABLE FOR
INPUT/OUTPUT DEVICES.
 THESE STATEMENTS CAN BE CLASSIFIED INTO THREE BROAD
CATEGORIES. THESE ARE:
 CONSOLE I/O - function to receive input from keyboard and write the
output to VDU or monitor.
 DISK I/O FUNCTIONS - function to perform i/o operations on storage
media such as floppy disk or hard disk.
 PORT I/O FUNCTIONS - function to perform i/o operations on various
operations on various output ports.
Console Input/output Functions:

Console I/O functions

Formatted functions Unformatted functions


Console Input/output Functions:

Formatted functions Unformatted functions


Type Input Output Type Input Output

getch()
putch()
char scanf() printf() char getchar()
putchar()
getche()
printf() -- --
int scanf() int
printf() -- --
float scanf() float
printf() -- --
string scanf() string
gets() puts()
Operators in C :
 AN OPERATOR OPERATES ON VARIABLES AND PERFORMS AN
ACTION IN A PROGRAM.
 IT CONSISTS OF WORDS OR SYMBOLS.
 FOR EXAMPLE, THE ARITHMETIC OPERATORS (+) AND (-) CAUSE US
TO ADD OR SUBTRACT TWO NUMBERS RESPECTIVELY.
 OPERATORS IN C LANGUAGE MAY BE CLASSIFIED AS:
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Pointer operators
 Special operators
 Bitwise operators
Arithmetic Operators :
Operator Symbol Form Operation

Multiplication * i*j i times j

Division / i/j i divided j

remainder of i
Remainder % i%j
divided by j

Addition + i +j i is added to j

i is subtracted from
Subtraction - i-j
j

Increment ++ i++ i is incremented by 1

Decrement -- i-- i is decremented by 1


Relational operators :

Operator Action

> Greater than

>= Greater than equal to

< Less than

<= Less than equal to

== Equal

!= Not equal
Logical operators :

Operator Action

&& AND

|| OR

! NOT
Assignment Operator:
Operator Action
= Assignment

+= Add the value of second operand to the first operand


and assigns the result to the first operand

-= Subtract the value of second operand from the first


operand and assigns the result to the first operand

*= Multiples the value of second operand with the first


operand and assigns the result to the first operand

/= Divide the value of first operand by the second


operand and assigns the result to the first operand

%= Divide the value of first operand by the second


operand and assigns the remainder to the first
operand
Bitwise Operators:
Operator Action
Binary AND Operator copies a bit to the result if it
&
exists in both operands.
Binary OR Operator copies a bit if it exists in either
|
operand.

Binary XOR Operator copies the bit if it is set in one


^
operand but not both.

Binary Ones Complement Operator is unary and has


~
the effect of 'flipping' bits.
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the
right operand.
Binary Right Shift Operator. The left operands value
>> is moved right by the number of bits specified by the
right operand.
Misc Operators:
Operator Action

sizeof() Returns the size of an variable.

& Returns the address of an variable.

* Pointer to a variable.

?: Conditional Expression
Operator Precedence:
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
C Datatypes :
DataTypes Size (bytes) Range

int 2 -32,768 to 32,767

signed int 2 -32,768 to 32,767

unsigned int 2 0 to 65535

short int 1 -128 to 127

Integer signed short int 1 -128 to 127


Date Type
unsigned short int 1 0 to 255

-2,147,483,648 to
long int 4
2,147,483,647

signed long int 4 Same as Above

unsigned long int 4 0 to 4,294,967,295


C Datatypes (cont..) :

DataTypes Size (bytes) Range

float 4 3.4E-38 to 3.4E+38


Floating
point double 8 1.7E-308 to 1.7E+308
Date Type
long double 10 3.4E-4932 to 1.1E+4932

char 1 -128 to 127

Character signed char 1 -128 to 127


data types
unsigned char 1 0 to 255
CHAPTER - 2
• Decision Making Statement
 if
 if-else
 if-else-if
 switch
 Nested switch
• Looping Statement
 for
 while
 do-while
CHAPTER – 2 (cont..)
• Jump Statement
 break
 continue
 Goto
• Conditional Statement
• Type Casting
Decision Making Statement:
if :
 It takes an expression in parenthesis and an statement or block of
statements in its body.
 If the expression is true then the statement or block of statements gets
executed otherwise these statements are skipped.
Syntax:
if(Expression)
{
Block of statement;
}
Decision Making Statement:
if-else :
 It takes an expression in parenthesis and an statement or block of
statements.If the expression is true then the statement or block of
statements gets executed otherwise else part statement is executed.
Syntax:
if(Expression)
{
Block of statements;
}
else
{
Block of statements;
}
Decision Making Statement:
Nested if : if-else-if :
Syntax: Syntax:
i f(Expression)
i f(Expression)
{
{
Block of statement;
if(Expression)
}
Block of statement
Else if(expression)
else
{
Block of statement;
Block of statement;
}
}
Else
Else
{
{
Block of statement;
Block of statement;
}
}
Decision Making Statement:
Switch Statement:
Syntax:
switch(expression)
{
case constant-expression :
statement(s);
break;/* optional */
case constant-expression :
statement(s);
break;/* optional */
default :/* Optional */
statement(s);
}
Looping Statement:
Loop Type Description Syntax

Repeats a statement or group of


statements while a given condition
while loop for(INITIALIZATION;CONDITION;AFTERTHOUGHT){ }
is true. It tests the condition before
executing the loop body.
Execute a sequence of statements
multiple times and abbreviates the while (test expression) {statement/s to be
for loop
code that manages the loop executed. }
variable.

Like a while statement, except that


do...while
it tests the condition at the end of do { some code/s;}while (test expression);
loop
the loop body

You can use one or more loop


nested loops inside any another while, for or
do..while loop.
Jump Statement

Control Statement Description

Terminates the loop or switch statement


break statement and transfers execution to the statement
immediately following the loop or switch.

Causes the loop to skip the remainder of


continue statement its body and immediately retest its
condition prior to reiterating.

Transfers control to the labeled statement.


goto statement Though it is not advised to use goto
statement in your program.
Conditional Statement

 C ternary operator is also referred as conditional operator or


ternary operator because:
 It is only the operator that has three operands.
 It is shorthand of combination of the if-else and return statement.

 The syntax of C ternary operator is as follows:

condition?expression 1 : expression 2
Type Casting
 Type casting is a way to convert a variable from one data type to
another data type.
 For example, if you want to store a long value into a simple integer
then you can type cast long to int.
 You can convert values from one type to another explicitly using the
cast operator as follows:

(type_name) expression
CHAPTER - 3
 Functions
 Function Definition
 Function Declaration
 Function Calling
 Function Argument
 Function return values
 Recursion
 Arrays
 1 Dimensional Array
 2 Dimensional Array
CHAPTER – 3 (cont..)
 String Function
 Strlen()
 Strlwr()
 Strupr()
 Strcat()
 Strcpy()
 Strrev()
 Strcmp()
Function
 A function is a group of statements that together perform a
task. Every C program has at least one function, which is
main().
 A large C program is divided into basic building blocks
called C function.
 C function contains set of instructions enclosed by “{ }”
which performs specific operation in a C program.
 Actually, Collection of these functions creates a C
program.
Function ( cont..)
Types of C functions :
There are two types of functions in C programming:
 Library function
 User defined function
Library function : Library functions are the in-built function
in C programming system.
Eg : printf(), scanf(),. etc
User defined function : C allows programmer to define
their own function according to their requirement. These
types of functions are known as user-defined functions.
Function ( cont..)
User defined function :
Syntax :
Function ( cont..)
Defining a Function: The general form of a function
definition in C programming language is as follows :
Syntax :
return_type function_name( parameter list )
{
//Body of the function
}
Function ( cont..)
Defining a Function (cont..):
• Return Type: A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the keyword
void.

• Function Name: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.

• Parameters: A parameter is like a placeholder. When a function is


invoked, you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and number
of the parameters of a function. Parameters are optional; that is, a function may
contain no parameters.

• Function Body: The function body contains a collection of statements


that define what the function does.
Function ( cont..)
Function Declaration: A function declaration tells the
compiler about a function name and how to call the function.
The actual body of the function can be defined separately.

A function declaration has the following parts:


return_type function_name( parameter list );
Function ( cont..)
Calling a Function:When a program calls a function, program control is
transferred to the called function. After executing the called function it returns
program control back to the main program.
#include<stdio.h>
/* function declaration */
int max(int num1,int num2); int max(int num1,int num2)
{
int main () /* local variable declaration */
{ int result;

int a =100; if(num1 > num2)


int b =200; result= num1;
else
int ret;
result= num2;
/* calling a function to get max value */
ret= max(a, b); return result;
}
printf("Max value is : %d\n", ret );
return0;

}
Function ( cont..)
Function Arguments:If a function is to use arguments, it must declare
variables that accept the values of the arguments. These variables are called the
formal parameters of the function.
While calling a function, there are two ways that arguments can be passed to a
function:

Call Type Description

This method copies the actual value of an argument into the


formal parameter of the function. In this case, changes made to
Call by value
the parameter inside the function have no effect on the
argument.

This method copies the address of an argument into the formal


parameter. Inside the function, the address is used to access the
Call by reference
actual argument used in the call. This means that changes
made to the parameter affect the argument.
Function ( cont..)
Return Statement : Return statement is used for returning a value from
function definition to calling function.

Syntax: return (expression);


Example :

return a;
return (a+b);
Function ( cont..)
Recursion : Recursion is the process of repeating items in a self-similar way.
Same applies in programming languages as well where if a programming allows
you to call a function inside the same function that is called recursive call of the
function.

Example :
#include<stdio.h>
int factorial(unsignedint i) int main()
{
{ int i =15;
if(i <=1) printf("Factorial of %d is %d\n", i, factorial(i));
return0;
{ }
return1;
}
return i * factorial(i -1);
}
String Function
 The string in C programming language is actually a one-dimensional array of characters
which is terminated by a null character '\0'.
 Thus a null-terminated string contains the characters that comprise the string followed
by a null.
 C provides an inbuilt library for string functions. To use these functions, you need to
include the header file
#include<string.h>
S.N. Function Purpose Example

1 strcpy(s1, s2); Copies string s2 into string s1. strcpy(dest1,dest)t I


2 strcat(s1, s2); Concatenates string s2 onto the end of string s1. strcat(dest, “Friends”)

3 strlen(s1); Returns the length of string s1. int i=strlen(source)


Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; int i= strcmp(str1,str2)
4 strcmp(s1, s2);
greater than 0 if s1>s2.
Returns a pointer to the first occurrence of character ch in char *strchr(const char *str)
5 strchr(s1, ch);
string s1.
Returns a pointer to the first occurrence of string s2 in string char *strstr(const char *s1,
6 strstr(s1, s2); s1. const char *s2)

7 strupr() Convert the String into uppercase strupr(dest, source)


8 strrev() Reverse the string strrev(source)
9 strlwr() Convert the String into lowercase strlwr(dest, source)
Array
 C programming language provides a data structure called
the array, which can store a fixed-size sequential
collection of elements of the same type.
 An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables
of the same type.
 The lowest address corresponds to the first element and
the highest address to the last element.
Why Array index starts with zero?
 Physical Address + (difference in bytes * Starting index).
 FORTRAN is the language where array index starts from 1.

Declaring Arrays:
type arrayName [ arraySize ];
type arrayName[arraySize][array Size];

Example :
double balance[10];
double balance[10][10];
Initializing Arrays
 double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

Accessing Array Elements :


double salary = balance[3];
• The above statement will take 4th element from the array and assign
the value to salary variable.
Two Dimensional Arrays
 Two dimensional arrays is nothing but array of array.

Initialization of Multidimensional Arrays:


int c[2][3]={{1,3,0}, {-1,5,9}};
OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR
int c[2][3]={1,3,0,-1,5,9};
Initialization Of three-dimensional Array:
doublecprogram[3][2][4]={
{ {-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2} },
{ {0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}},
{ {8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0} }
};
C Programming Arrays and Functions
 Passing One-dimensional Array in Function

#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main()
{
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
}
Chapter - 4

Pointers and Dynamic Memory :


A pointer is the memory address of a variable.

A memory address is a physical location within a system’s memory space.

A pointer variable is variable used to hold a pointer.


It is a special data type.
Pointers and Dynamic Memory

A pointer variable can be assigned a pointer


(memory address).

We can declare a pointer variable:

int * myIntPtr;

Type of data pointed to (int), pointer symbol (*),


variable name (myIntPtr).
Pointers and Dynamic Memory

We can assign a memory address (pointer) to the


variable: (& is called the address-of operator)

myIntPtr = &myInt;

Where: int myInt was declared earlier in the program.


Pointers and Dynamic Memory

We can refer to the value in the location pointer to by myIntPtr


with the dereferencing operator * as follows:

cout << *myIntPtr << endl;

If we had previously executed the statement


int myInt =42;

We would see ‘42’ in the output.


Pointers and Dynamic Memory

Pointers can be set with the usual assign operator.

int i = 42;
int * p1, *p2;
p1 = &i; 42 int i

int *p2
int *p1

Before
Pointers and Dynamic Memory

Pointers can be set with the usual assign operator.

int i = 42;
int * p1, *p2;
p1 = &i; 42 int i
//--------------
p2 = p1;

int *p2
int *p1

After
Pointers and Dynamic Memory

Contents of pointer variables can be set with the


assign operator.

17 int j
int i = 42; 42 int i
int j = 17
int * p1, *p2;
p1 = &i;
p2 = &j;

int *p2
int *p1

Before
Pointers and Dynamic Memory

Contents of pointers variables can be set with the assign


operator.

17 int j
*p1 = *p2; 17 int i

int *p2
Value of location pointed int *p1
to by p2 copied to
location pointed to by p1 After
Pointers and Dynamic Memory

The real power of pointers is seen


when they are used to point to
dynamically allocated variables.

Let’s see why.


Pointers and Dynamic Memory

Dynamic variables are used just like ordinary static variables


except:

•They are not declared, so they have no identifiers like static


variables do.

•They are created during run time, not when the program is
compiled.
Pointers and Dynamic Memory

Storage for these variables comes from an area of memory called


the free store or the heap.

The creation of new dynamic variables is called memory allocation


and the memory is called dynamic memory.

C++ uses the new operator create a dynamic variable.


Pointers and Dynamic Memory

Here are the steps:

int * myIntPtr; // create an integer pointer variable


myIntPtr = new int; // create a dynamic variable
// of the size integer

new returns a pointer (or memory address) to the location where the
data is to be stored.
Pointers and Dynamic Memory

Free Store (heap)

int * myIntPtr
myIntPtr = new int;
myIntPtr
Pointers and Dynamic Memory

Use pointer variable as before


Free Store (heap)

12 3
int * myIntPtr
myIntPtr = new int;
myIntPtr

*myIntPtr = 123;
Pointers and Dynamic Memory

We can also allocate entire arrays with the new operator.


These are called dynamic arrays.

This allows a program to ask for just the amount of memory


space it needs at run time.
Pointers and Dynamic Memory
Free Store (heap)

0 myIntPtr
int * myIntPtr;
myIntPtr = new int[4];
1 3 2 5
2
3 myIntPtr[1] = 325;

Notice that the pointer symbol is


understood, no * is used to reference
the array element.
Pointers and Dynamic Memory

The new operator gets memory from the free


store (heap).

When you are done using a memory location,


it is your responsibility to return the space to
the free store. This is done with the delete
operator.

delete myIntPtr; // Deletes the memory


pointed
delete [ ] arrayPtr; // to but not the pointer
variable
Pointers and Dynamic Memory

Dynamic memory allocation provides a


more flexible solution when memory
requirements vary greatly.

The memory pool for dynamic memory


allocation is larger than that set aside for
static memory allocation.

Dynamic memory can be returned to the


free store and allocated for storing other
data at later points in a program. (reused)
Pointers and Arrays as Parameters

int *main_ptr;
main_ptr = new int;
222

set_value(main_ptr); main_ptr

-----------------------------------------
void set_value(int * tempPtr)
{
tempPtr
*tempPtr = 222;
}
Pointers and Arrays as Parameters

int *main_ptr;
main_ptr = new int[4];

set_value(main_ptr); main_ptr
222
-----------------------------------------
void set_value(int tempPtr[])
{
tempPtr
tempPtr[1] = 222;
}
Pointers and Arrays as Const
Parameters
int *main_ptr;
main_ptr = new int[4];

set_value(main_ptr); main_ptr
-----------------------------------------
void set_value(const int
tempPtr[])
{
tempPtr[1] = 222;
} Not allowed
Pointers and Dynamic Memory

Sometimes we may want a function to change a pointer so


that it points to a different location

This is accomplished by using a reference parameter that is a


pointer type

void change_location(int* & refPtr)


Pointers and Dynamic Memory

We often use a typedef statement to simplify the


cumbersome syntax.

typedef int* inPtr;

inPtr myIntPtr;

void functionEx(inPtr & localPtr);


Pointers and Dynamic Memory

Some things to be careful with when using pointers.

Pointers should always point to something. When a object pointed to is no


longer needed, the memory should be freed with delete and the pointer
should be assigned the special value null, defined in the stddef.h header
file.

delete myIntPtr; // return memory to free store


myIntPtr = null; // point to special “nothing” value.
Pointers and Dynamic Memory

A pointer not pointing to an object is considered “unassigned”.

An unassigned pointer variable must not be dereferenced.

A “null” pointer value should not be dereferenced.

A pointer left pointing is called a dangling pointer.


Pointers and Dynamic Memory

Dangling pointers can occur when two or more pointers point to


the same object and one of the pointers is used with the delete
operator.

42 Returned to
42 Delete p1; free store

int *p2 int *p1


int *p1
int *p2
A dangling pointer
Pointers and Dynamic Memory

An inaccessable memory location, also called a memory leak,


results from the reassignment of a pointer without first releasing
the memory it pointed to.

42 17 42 17

An inaccessable
object
int *p1 int *p2 int *p1 int *p2

p2 = p1;
Pointers and Dynamic Memory

An inaccessable memory location can also be caused by


inappropriate use of new operator.

42 42

An inaccessable
object
int *p1 int *p1

p1 = new int;
Pointers and Dynamic Memory

Pointers also introduce potential problems with the behavior of the


automatic assignment operator, the copy operation, and the
comparison operation.

The automatic behavior produces what is called a shallow copy.


Both pointers point to the same object. What we want is a deep
copy. We want a copy of the data not just the pointer.
Pointers and Dynamic Memory

What we wanted.

0 0 int * myIntPtr;
1 1 myIntPtr = new int[4];
myIntPtr
2 2 int * myIntPtr2;
3 3 myIntPtr2 = myIntPtr;

myIntPtr2
Not the default
behavior of ‘=‘
Free Store (heap)
Pointers and Dynamic Memory

What we got!

0 int * myIntPtr;
1 myIntPtr = new int[4];
myIntPtr
2 int * myIntPtr2;
3 myIntPtr2 = myIntPtr;

myIntPtr2

Free Store (heap)


Pointers and Dynamic Memory

To handle this and other dynamic data situations, we must add


additional member functions to any class that uses dynamic data.
Some additional functions would want:

We must overload the assignment operator.

We must provide a copy constructor.

We also need to add a destructor member function.


Pointers and Dynamic Memory

Let’s look at the copy constructor. The principles are the same for
the assignment operator overload.

A copy constructor is a special constructor called when a new


instance of a class is created from an existing object of that
class.

DynamicClass newClass(oldClass);

DynamicClass newClass = oldClass;


Pointers and Dynamic Memory

Class DynamicClass
{
public:
DynamicClass (const DynamicClass & oldClass);
void operator =(const DynamicClass & oldClass);
~DynamicClass ();


};
Pointers and Dynamic Memory

DynamicClass::DynamicClass
(const DynamicClass& oldClass)
{
data = new Item[someSize];
for (int i=0; i < oldClass.currentSize; i++)
{
data[i] = oldClass[i];
}
}
Pointers and Dynamic Memory

0 A 0 A oldClass
data
1 B 1 B
2 C 2 C
3 D 3 D

Free Store (heap)


Pointers and Dynamic Memory

Now let’s apply what we’ve learned to resizing a dynamically


allocated array.

When the capacity of the original array is used up, we want to


allocate a new larger array and copy the data from the original
array to the new larger array.

After the data has been copied, we can delete the original
array and return the memory to free store.
Pointers and Dynamic Memory

0 A A
0 oldClass
1 B 1 B
data
2 C 2 C
3 D 3 D
4
5
6
Pointers and Dynamic Memory

delete [ ] oldClass;

0 A A
0 oldClass
1 B 1 B
data
2 C 2 C
3 D 3 D
4
5 Return
memory
6
Pointers and Dynamic Memory

Class DynamicClass
{
public:
DynamicClass (const DynamicClass & oldClass);
void operator =(const DynamicClass & oldClass);
~DynamicClass ();


};
Pointers and Dynamic Memory

When we are finished using a class instance, we must free any memory
pointed to by variables in the class. This is done automatically by invoking
the code contained in the class destructor. Failure to do so creates
memory leaks.

Like the constructor, the destructor does not return any data type. It has
the same name as the class name but is preceded by the ‘ ~’ symbol.
DynamicClass:: ~DynamicClass() { }
Pointers and Dynamic Memory

The use of pointers and dynamic variables is an important


problem solving tool. It gives the class builder flexibility in managing memory.

It’s use does require more care on the part of the programmer, since control
is now in the hands of the programmer and not the system.

However, the benefits generally outweigh the disadvantages and C++


programs make heavy use of dynamic memory.
Chapter 5
 Structure
 Structure using Function
 Structure using Pointer
 Union
 Difference Between Structure and Union
Structure
 Structure is the collection of variables of different types
under a single name for better handling.
 For example: You want to store the information about
person about his/her name, citizenship number and
salary.
 You can create this information separately but, better
approach will be collection of this information under
single name because all these information are related to
person.
Structure Definition in C
 Keyword struct is used for creating a structure.
Syntax of structure:
struct structure_name
{
data_type member1;
.
.
data_type memeber;
};
Example:
struct person
{
char name[50];
int cit_no;
float salary;
};
Structure variable declaration
struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];

In this case, 2 variables p1, p2 and array p having 20 elements of type


struct person are created.
Accessing members of a structure
There are two types of operators used for accessing members of a
structure.
I. Member operator (.)
II. Structure pointer operator(->)

Any member of a structure can be accessed as:


structure_variable_name.member_name
Keyword typedef while using structure
 Programmers generally use typedef while using structure in C
language.
 For example:
typedef struct complex
{
int imag;
float real;
} comp;
Inside main:
comp c1,c2;
 Here, typedef keyword is used in creating a type comp(which is of type as
struct complex). Then, two structure variables c1 and c2 are created by this
comp type.
Structures within structures
 Structures can be nested within other structures in C programming.
 For example:
struct complex
{
int imag_value;
float real_value;
};
struct number{
struct complex c1;
int real;
} n1,n2;
 Suppose you want to access imag_value for n2 structure variable then,
structure member n1.c1.imag_value is used.
Pointers to Structures
Syntax:
struct name {
member1;
member2;
.
.
};
-------- Inside function -------
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
Pointers to Structures
 Structure pointer member can also be accessed using -> operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b

Accessing structure member through pointer using dynamic


memory allocation :

 To access structure member using pointers, memory can be allocated


dynamically using malloc() function defined under "stdlib.h" header file.
Syntax to use malloc()
ptr=(cast-type*)malloc(byte-size)
UNION
 Unions are quite similar to the structures in C.
 Union is also a derived type as structure.
 Union can be defined in same manner as structures just the keyword used in
defining union in union where keyword used in defining structure was struct.
 Syntax :
union car{
char name[50];
int price;
};

 Example :
union car{
char name[50];
int price;
}c1, c2, *c3;
Difference between union and structure
Structure Union
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.

2. When a variable is associated with a structure, the 2. When a variable is associated with a union, the
compiler allocates the memory for each member. The compiler allocates the memory by considering the
size of structure is greater than or equal to the sum of size of the largest memory. So, size of union is equal
sizes of its members. The smaller members may end to the size of largest member.
with unused slack bytes.

3. Each member within a structure is assigned unique 3. Memory allocated is shared by individual
storage area of location. members of union.
4. The address of each member will be in ascending 4. The address is same for all the members of a
order This indicates that memory for each member will union. This indicates that every member begins at
start at different offset values. the same offset value.
5 Altering the value of a member will not affect other 5. Altering the value of any of the member will alter
members of the structure. other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.

7. Several members of a structure can initialize at 7. Only the first member of a union can be
once. initialized.

Das könnte Ihnen auch gefallen