Uploaded by Anil Kishan P

c notes ver1

advertisement
UNIT – III (Pointers and Strings) Pointers – Introduction (Basic Concepts), Pointers for inter function
communication, pointers to pointers , compatibility, Pointer Applications-Arrays and Pointers, Pointer
Arithmetic and arrays, Passing an array to a function, memory allocation functions, array of pointers,
programming applications, pointers to void, pointers to functions. Strings – Concepts, C Strings, String Input
/ Output functions, arrays of strings, string manipulation functions, string / data conversion,
Pointers:Pointer is a variable which holds address of another variable.
Declaration Syntax: datatype *ptr;
Example: int *p;
Initialization Syntax:datatype *ptr = &variable;
Features of pointers:1.Its size is equal to unsigned integer specified by compiler i,e 2 or 4 bytes.
2.%u is used to show the value of addresses in formatted output function printf
3.To access value at address of pointer * is used before variable.
4. * is called Indirection/redirection/dereferencing operator.
4.To assign a value to a pointer & is used before variable of compatable type.
5.The size of any type of pointers are same.
6.Void pointer can’t be dereferenced
7.Pointers are flexible, improves speed of execution.
Pointer Flexibility:
pointers are variables their addresses can be changed ,
Group of pointers can hold address of same location.
Advantages of pointers:1.efficient and fast data access and manipulation
2.Used in call by reference/address in functions.
3.Decreases overhead of passing large information/data during function calls
4.Decreases variable declarations, values duplications if arised during programming.
5.It is used to access arrays efficiently.
6.It is used to handle Dynamic memory allocation blocks.
Disadvantages/Drawbacks of pointers:1.Dangling pointer may arise: which dont points to a valid object of the appropriate type.
2.Null pointer exception may arise. Accessing a pointer with no address may lead to run time errors.
3. Security issues:Manipulation on memory may give programmers to access unknown locations which
increases risks of security and threats.
4.Segmentation fault: Which happens during dynamic memory allocations or dereferencing Null pointers.
5.Hard to debug:removing errors becomes complex.
6.Memory leaks: Which arise during dynamic memory handling if free() is not used after allocation.
Explain Pointers for Inter function communication : It is possible to send information of pointer to
function and getting information from function as a pointer in two types.
1.passing pointers to a function as parameter 2.getting pointer from a function as return value.
1.passing pointers to a function or call by reference or call by Address.
In function parameter passing techniques we have
1.downward
2.upward
3.bidirectional
upward and bidirectional function communication needs pointer variables in function parameters.
Pointer to pointer: is a variable which holds address of another pointer.
Declaration Syntax: datatype **p2p;
Example: int **p2p;
Initialization Syntax:datatype *p2p = &ptr;
Pointer Compatability: It is divided into three types
Size Compatability:
Dereference type Compatability:
Dereference level Compatability:-
Size Compatability: sizes of all pointers are same.
Deference type Compatability:
Although the sizes of all pointers are same,assignment of addresses to incompatible types may lead to
compile errors.
Dereference level Compatability:-pointers store metadata called addresses to facilitate fast data
manipulation,pointer to pointers are called level 2 pointers, comple time errors will occur even if we assign
misplaced
example :if we assign address of basic data type variables to pointers to pointers we get Dereference level
Incompatability
Pointer Applications:-There are 3 basic uses of pointers.
1.Pointers with arrays.
2.Pointers with Dynamic memory Handling.
3.String Handling
Pointers with arrays(Pointer Arithmetic):The name of array is address/pointer constant of first location.
Pointers can be assigned with addresses of arrays.There are two types
1.Pointers with 1-D Arrays
2.Pointer with 2-D Arrays
Pointer Arithmetic:The valid arithmetic operations that can be performed on pointers are
1.Addition and 2. Subtraction with an integer,
subtraction can be done on two pointers which results index gap between two elements if they belong to
same array elements.all below are valid operations on pointers.
p+5
p-5
p++
--p
p1-p2
Relational operators can be used on pointers but valid only to find order if they belong to same array group,
but most useful/common relational expression is comparing pointer with NULL
if(p==NULL)
Passing an Array to function:
Array:Array is a Collection of similar data items, which are stored in adjacent memory locations and can be
referred by a common name and diffrent index values.
Syntax: datatype var[size];
example: int a[50];
Function:It is an independent module that will be called to do a specific task.It is a named independent
module with Block of statements, which may have finite number of inputs and a return value.
Syntax:
returntype functionname()
{
stmt; ...
}
To pass a 1D Array to function , we must declare as per the following syntax
returntype functionname(datatype arrayname[size]);
eg: int sum(int[ ]);
returntype functionname(datatype arrayname[][size1][size2]);
eg: int sum(int[ ][2][3]);
Example Program:- Write a program to print sum of numbers using passing 1D Array to function.
#include<stdio.h>
int sum(int[ ]);
void main()
{
int a[ ]={1,2,3};
int res;
res=sum(a);
printf(“sum=%d”,res);
}
int sum(int a[ ])
{
int i,add=0;
for(i=0;i<3;i++)
{
add+=a[i];
}
return add;
}
Expected output:
sum=6
Example Program:- Write a program to
print sum of all numbers using passing
2D Array to function.
#include<stdio.h>
int sum(int[ ][3]);
void main()
{
int a[ ][]={{1,2,3},{1,2,3}};
int res;
res=sum(a);
printf(“sum=%d”,res);
}
int sum(int a[ ][3])
{
int i,j,add=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
add+=a[i][j];
return add;
}
Expected output:
sum=12
Memory allocation functions:Memory required to run a Program is divided into functions and data, all
functions are stored in program memory, data is either stored as globals,or as heap,or as stack in Memory.
Allocation in C language can be either
1: Static 2.Dynamic
All variables declared inside function are called static allocations, the number of bytes reserved cant be
changed during runtime for static allocations.C uses stack memory to handle static memory allocations.
Dynamic memory Handling Functions:There are four memory handling functions to allocate memory at
runtime .these uses a special heap memory.
1.malloc :Allocated memory at runtime
2.calloc :Clears to Zero and Allocated memory at runtime
3.realloc : Resizes memory Allocation at runtime.
4.free :Deallocates Memory
Array of Pointers or Ragged Array:collection of pointers which are stored in adjacent memory locations
and can be referred by a common name and diffrent index values.
Syntax: datatype *var[size];
example: int *a[50];
Eg:
int *table[3];
int t1[]={1,2,3,4};
int t2[]={5,6};
int t3[]={7,8,9};
table[0]=&t1[0];
table[1]=&t2[0];
table[2]=&t3[0];
Pointer to void:It is also called generic Pointer, which can be used by any type at runtime or compile time.It
is not null pointer.it is generally used in dynamic memory handling functions.
Syntax: void *ptr;
Pointer to function : Its is a variable which holds address of function.Like variables functions also occupy
memory, to hold their addresses pointers to function are used.
Declaration Syntax: returntype (*fp)(parameterlist);
Assignment Syntax:fp=functionname;
Usage Syntax:(*fp)(parameters)
For example:Program to Print 9 to 1
#include<stdio.h>
void main()
{
void (*fp)();
fp=main;
static int i=10;
if(--i==0)
return;
else
{
printf("%d,",i);
(*fp)();
}
}
expected output:9,8,7,6,5,4,3,2,1,
Strings: Sequence of characters enclosed in double quotes is called String.
Array of Characters is called String.
Example: "Hello World"
Two types of String variable declarations are possible
1.Using Arrays(3 types) 2.Using Pointer
char a[20]="jntu";
char b[ ]="jntu";
char c[ ]={'b','a','t','\0'};
char *p="hyd";
The sizes of a ,b,c and p are 20,5,4,4 bytes.
The String lengths of a,b ,cand p are 4,4,3,3.
Features/Concept of String:C uses Variable length delimited Strings.
The strings in C are delimited by Null Character '\0' at end.
%s is format specifier used to read or write Strings to IO devices.
String Functions :- String or Character functions are defined in stdlib.h,ctype.h , string.h ,stdio.h header
files.String Functions are divided into two types
1.String IO Functions:printf, scanf , gets ,puts ,sscanf , sprintf , fscanf , fprintf
2.String Manipulation Functions:strlen, strcpy, strncpy, strcmp, strncmp,strcat,strncat,strchr,strrchr, strstr,
strspn, strcspn,strpbrk,strtok,strtol,strtod, strtold,strtof,strtoll,strtoul,strtoull,wcstol d,wcstof, wcstoll,
wcstoul, wcstoull,wcstol,wcstod.
S.
NO
Syntax
1
printf(formattedstring,parameters); Prints formatted string
Sucessful outputs
2
scanf(formattedstring,Addresses); Reads formatted string
Sucessful inputs
3
gets(stringvariable);
Reads string
4
puts(string);
Prints string
5
strlen(String);
Finds string length
6
strcpy(strvar,string);
Copies String
7
strncpy(strvar,string,noofchar);
Copies n characters
8
strcmp(string1,string2);
Compares 2 strings
Ascii of str1 - str2
9
strcnmp(string1,string2);
Compares 2 strings to n
Ascii of str1 - str2
10 str3=strcat(string1,string2);
Concatenates string2 to String1
Concatenated string
11 str3=strncat(string1,string2);
Concatenates n char of str2 to Str1 Concatenated string
12 ptr=strchr(str,ch);
Returns address of ch in str
13 ptr=strrchr(str,ch);
Gives address of ch in str from end Address of ch from rear
14 ptr=strstr(str,substr);
Finds substring in str
Returns address of substr
15 len=strspn(str1,charsetstr);
Returns str1 span from charset
Length of span String
16 len=strcspn(str1,charsetstr);
Complement span
Length of string till span
17 ptr=strpbrk(str,setstr);
Same as strcspn but returns char*
Returns pointer
18 ptr=strtok(str,delimiterstr);
Keeps null char in str for delimiter String after delimiter
19 longvar=strtol(str,remstr,base)
Converts number in str to base
longvar
20 doublevar=strtod(str,remstr)
Converts to double in str
doublevar
21 sprintf(str,formattedstr,param);
Sends formatted str to var str
Sucessful outputs to str
Functionality
22 sscanf(str,formattedstr,addparam); Sends str info to addparam
Return value
Stringlength
Address of ch
Sucessful inputs to param
String/Data Conversion: C is first Language to Introduce Data Types, It provides Large set of Data types
Which includes Basic data types like int,char,float,double,long etc and derived data types like String,
Pointers, Structures, Enums, Unions etc. Since Data flows in communication technologies mostly in text
streams, Conversions between String to Data are important.There are two types of conversions
1.String to Data Conversion.
2.Data to String Conversion.
String to Data Conversion:The information in str is sent to data items as per specified formatted string.
sscanf(str,formattedstr,addparam); Sends str info to addparam
Sucessful inputs to param
strtol,strtod,strtold,strtof,strtoll,strtoul,strtoull: Converts string to specified data types.
wcstol,wcstod,wcstold,wcstof,wcstoll,wcstoul.wcstoull, Converts Wide Character String to specified types.
Data to String Conversion.The information in data items is sent to str as per specified formatted string.
sprintf(str,formattedstr,param);
Sends formatted str to var str
Sucessful outputs to str
UNIT – IV(Structures, Unions, Enums,typedef, Preprocessor Commands)Enumerated types, Structure and
Union Types – The Type Definition (typedef), Enumerated types, Structures –Declaration, initialization,
accessing structures, operations on structures, Complex structures-Nested structures, structures containing
arrays, structures containing pointers, arrays of structures, structures and functions, Passing structures
through pointers, self referential structures, unions, bit fields, command–line arguments, Preprocessor
commands.
Enumerated Types or enum:enums are user defined types which encapsulates integers/numbers to
enumerated constants or enum identifiers.
There are three types of enums
1.Implicit enums
2.Explicit enums
3.Anonymous enums
Implicit enums.
Syntax: enum datatypename {id1,id2,id3,id4};
eg:
enum month {jan,feb,mar};
Compiler implicitly assigns 0 to jan, 1 to feb, 2 to mar.
Explicit enums:There are two types of explicit enums
1.Automated explicit enums 2.Fully explicitly defined enums
Automated explicit enums
Syntax: enum datatypename {id1=int1,id2,id3,id4};
eg:
enum month {jan=1,feb,mar};
Compiler automatically assigns incremented values i,e 2 to feb, 3 to mar.
Pure explicit enums
Syntax: enum datatypename {id1=int1,id2=int2,id3=int3,id4=int4};
eg:
enum month {jan=1,feb=2,mar=3};
Anonymous enums: Values to these types of enums can be done implicity or explicitly
Syntax: enum {id1,id2,id3,id4};
eg:
enum {on,off};
Compiler implicitly assigns 0 to on, 1 to off.
Declaring enum Variables:
Syntax: enum datatype var;
eg:
enum month m1=jan,m2=mar;
Operations on enum types:Like integer variables enum variables can be used for following
Assignment, Comparision,As an Integer value.
Enum constants/identifiers can be used as Integer constants or literals.
Structure:It is a collection of various related data items ,whose elements are accessed by a dot operator
which is preceeded by a common name or structure variable.
Dot operator(.) is called Direct Selection Operator.
Dot operator is postfix operator with priority 16.
Structure Declaration:- there are two ways to declare a structure
1. Tagged Structure 2.Using typedef
Tagged Structure starts with struct keyword.
Syntax:
struct Tag
{
field list
};
Example:
struct student
{
char name[40];
int rollno;
};
To create variables:
Syntax: struct student s1,s2;
struct with typedef.
Syntax:
typedef struct
{
field list
} type;
Example
typedef struct
{
char name[40];
int rollno;
}student;
To create variables:
Syntax: student s1,s2;
Initialization:
struct student s1={"jntustudent",34};
Accessing Structure variable elements:
To access values:
s1.name
s1.rollno
To access Addresses of elements:
&s1.rollno
which is same as &(s1.rollno), since dot has higher priority.
Operations on structure :Only Assignment is possible on structure variables, Comparision of two structure variables is not possible
due to slack bytes.
Pointers to Structures:-It is a variable which holds address of structure variable.
Structure Declaration:-Tagged Structure starts with struct keyword.
Syntax:
struct Tag
{
field list
};
Example:
struct student
{
char name[40];
int rollno;
};
Initialization:
struct student s1={"jntustudent",34};
Structure Pointer declaration:
struct student *p=&s1;
Accessing values of structure through pointers:
Indirect selection Operator(->)(minus greater than) is used to access values of structure pointer.
p->name
s1.name
(*p).name
p->rollno
s1.rollno
(*p).rollno
returns "jntustudent"
"jn returns 34
Program to illustarte Pointers to structure:#include <stdio.h>
void main()
{
struct student
{
char name[40];
int rollno;
};
struct student s1={"jntustudent",34};
struct student *p=&s1;
printf("\n a %s has rollno %d \n",p->name,p->rollno);
}
Expected Output:
a jntustudent has rollno 34
Complex Structures:-Structures are created to solve complex problems,it can be still redesigned to make
itself more complex to suit the solution to solve any complex problem designing new data types.
1.
2.
3.
4.
5.
Nested Structures: structures inside a structure
Structures containing arrays,
structures containing pointers,
Arrays of structures,
self referential structures: In a structure Each instance of the structure contains a pointer to
another instance of the same structure.
examples
1.
struct student
{
char name[40];
struct address
{
long pincode;
char house[90];
}ad;
}s1;
2.
3
4
5
struct student
{
char name[40];
int rollno;
}s1;
struct student
{
char name[40];
char *ptr;
}s1;
struct student
{
char name[40];
int rollno;
}s[10];
struct student
{
char name[40];
int rollno;
struct student *next;
}s1;
Passing Structure pointer to a function:
Passing/getting Structures to/from function:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
struct student
struct student
{
{
char name[40];
char name[40];
int rno;
int rno;
int m;
int m;
int credit;
int credit;
};
};
void correction(struct student*);
struct student correction(struct student);
void correction(struct student *s1)
struct student correction(struct student s1)
{
{
if(s1->m>=40)
if(s1.m>=40)
{
{
printf("pass");
printf("passed ");
s1->credit=4;
s1.credit=4;
}
}
else
else
{
{
printf("fail");
printf("failed ");
s1->credit=0;
s1.credit=0;
}
}
}
return s1;
void main()
}
{
void main()
struct student s1={"dummystudent",0,60};
{
printf("%d.%s got %d marks"
struct student s1={"dummystudent",0,60};
printf("%d.%s got %d marks",s1.rno,s1.name,s1.m); ,s1.rno,s1.name,s1.m);
correction(&s1);
s1=correction(s1);
printf("with %d credits",s1.credit);
printf("with %d credits",s1.credit);
}
}
Expected output:0.dummystudent got 60 marks passed with 4 credits
Self referential structures: In a structure Each instance of the structure contains a pointer to another
instance of the same structure.
Example:Program to illustrate Self referential structure.
#include<stdio.h>
struct singlelinkedlist
{
int data;
struct singlelinkedlist *next;
}n1,n2,n3,*node=&n1;
void main()
{
n1.data=10;
n2.data=20;
n3.data=30;
n3.next=NULL;
n1.next=&n2;
n2.next=&n3;
while(node!=NULL)
{
printf("%d ",node->data);
node=node->next;}} Expected output:10 20 30
Union :It is a collection of various related data items which share a common memory space , elements are
accessed by a dot operator which is preceeded by a common name or structure variable.
Dot operator(.) is called Direct Selection Operator.
Dot operator is postfix operator with priority 16.
Union Declaration:- there are two ways to declare a structure
1. Tagged union 2.Using typedef
Tagged Structure starts with union keyword.
Syntax:
union Tag
{
field list
};
Example:
union student
{
char name[40];
int rollno;
};
To create variables:
Syntax: union student s1,s2;
The Union follows the same syntax of Structures,but union allows memory to be shared by different types of
data.
Bitfields:Packed structures allow us to declare structures in a way that takes up a minimum
amount of storage.
For example, the following structure takes up six bytes (on a 16 -bit machine).
struct item {
unsigned int rollno;
unsigned int result1;
unsigned int result2;
};
the following structure takes up four bytes (on a 16 -bit machine).
struct item {
unsigned int rollno;
unsigned int result1:1;
unsigned int result2:1;
};
Commandline arguments:
The procedure main actually takes two arguments. They are called argc and *argv[]
example: program to print arguments in command line
#include<stdio.h>
void main(int argc,char *argv[])
{
int i;
for(i=0;i<argc;i++)
printf(" %d %s \n",i,argv[i]);
}
Preprocessor: It is a program which translates the source code to translatable code. Comipiler has
preprocessor and Translator
#include
#define
#undef
#(string conversion operator)
##(merge operator)
#if
#else
#endif
defined
#elif
#line
#error
#pragma
#(null command)
UNIT - I
Introduction to Computers – Computer Systems, Computing Environments, Computer
Languages, Creating and running programs, Program Development, algorithms and flowcharts ,
Number systems-Binary, Decimal, Hexadecimal and Conversions, storing integers and real
numbers.
Introduction to C Language – Background, C Programs, Identifiers, Types, Variables,
Constants, Input / Output, Operators(Arithmetic, relational, logical, bitwise etc.), Expressions,
Precedence and Associativity, Expression Evaluation, Type conversions, Statements- Selection
Statements(making decisions) – if and switch statements, Repetition statements ( loops)-while,
for, do-while statements, Loop examples, other statements related to looping – break, continue,
goto, Simple C Program examples.
UNIT - II
Functions-Designing Structured Programs, Functions, user defined functions, inter function
communication, Standard functions, Scope, Storage classes-auto, register, static, extern, scope
rules, type qualifiers, recursion- recursive functions, Limitations of recursion, example C
programs.
Arrays – Concepts, using arrays in C, inter function communication, array applications- linear
search, binary search and bubble sort, two – dimensional arrays, multidimensional arrays, C
program examples.
Unit 5(File Handling) Input and Output – Concept of a file, streams, text files and binary files, Differences
between text and binary files, State of a file, Opening and Closing files, file input / output functions
(standard library input / output functions for files), file status functions (error handling) Positioning functions
(fseek ,rewind and ftell),
missing topics need to cover:
type qualifiers,
binary search
Limitations of recursion
storing integers and real numbers.
Download