Beruflich Dokumente
Kultur Dokumente
Assistant Professor
UNIT 1
A. POINTERS
Example:
int *a;
Here the declaration of a pointer to be of type int *, the compiler assumes that any address that it
holds points to an integer— whether it actually does or not. (That is, an int * pointer always
''thinks" that it points to an int object, no matter what that piece of memory actually contains.)
Therefore, when the declaration of a pointer should start by its type which is compatible with the
type of object to which that it needs to point.
Here m is placed with the memory address of the variable count . This address is the
computer's internal location of the variable. It has nothing to do with the value of count.
The & is as returning "the address of." Therefore, the preceding assignment statement can
be verbalized as "m receives the address of count.”
c. * operator:
The second pointer operator, *, is the complement of &. It is a unary operator that returns the
value located at the address that follows.
Example:
q = *m;
If m contains the memory address of the variable count. M places the value of count into q.
Here q will have the value 100 because 100 is stored at location 2000, which is the memory
address that was stored in m. You can think of * as "at address." In this case, the preceding
statement can be verbalized as "q receives the value at address m."
a. Pointer can be used on the right-hand side of an assignment statement to assign its value to
another pointer.
b. When both pointers are the same type, the situation is straightforward.
c. Example:
1. #include <stdio.h>
2. int main(void)
3. {
4. int x = 99;
5. int *p1, *p2;
6. p1 = &x;
7. p2 = p1;
8. /* print the value of x twice */
9. printf(''Values at p1 and p2: %d % d\n", *p1, *p2);
10. /* print the address of x twice */
11. printf("Addresses pointed to by p1 and p2: %p %p", p1, p2);
12. return 0;
13. }
p1 and p2 both point to x. Thus, both p1 and p2 refer to the same object. Sample
output from the program is as follows.
Values at p1 and p2: 99 99
a. Definition: One type of pointer can be converted into another type of pointer.
b. Types of conversions:
i. By explicit casting
ii. By using void * pointer
Explanation:
i. Explicit casting:
Definition:
Conversions are done explicitly by users using the pre-defined functions.
Explicit conversions require a cast operator.
General Form:(type_name) expression
Where:
Type_name indicates to which type of data the expression
is converted.
Example:
#include <stdio.h>
Void main()
{
int sum = 17, count =
5; double mean;
Output:
10
a. There are only two arithmetic operations that you can use on pointers:
i. Addition
ii. Subtraction
b. Definition of addition:[Increment]
Each time a pointer is incremented, it points to the memory location of the next element
of its base type.
Example:
Let p1 be an integer pointer with a current value of 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.
c. Definition of subtraction:[Decrement]
== Equals
!= Not Equal
b. Example:
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;//If ptr1 is of address 1000 and ptr2 is of address
1002 if(ptr2 > ptr1)
printf("Ptr2 is pointing to higher memory location than
ptr1"); return(0);
}
The concept of array is very much bound to that of pointers. An array occupies consecutive
memory location. For example, if we have an array declared as, int arr[] = {1,2,3,4,5}; then in
memory it would be stored as shown below,
1 2 3 4 5
arr[0] arr[1] arr[2] arr[3] arr[4]
1000 1002 1004 1006 1008
Array notation is a form of pointer notation. The name of an array is the starting address of array
in memory. It is also known as base address. In other words, base address is the address of first
element in the array or the address of arr[0].
Now let us use the pointer variable as shown below,
int *ptr;
ptr=&arr[0];
here, ptr is made to point to first element of the array. Consider below example,
#include<stdio.h>
int main()
{
int arr[]={1,2,3,4,5};
printf(―\n address of array = %p %p %p‖, arr, &arr[0], &arr);
}
Output: address of array 1000 1000 1000
Because arr, &arr[0], &arr will give the address of the first element of an array.
int arr[]={1,2,3,4,5};
int *ptr;
ptr=arr; /*similar to ptr=&arr[0]*/ printf(―\n starting
address of array = %p‖, ptr);
}
Output: starting address of array 1000
In the above example, you are using pointer ptr, to point to the first element of an array.
Array of pointers
There may be a situation when we want to maintain an array, which can store pointers to an int or char or
any other data type available. Following is the declaration of an array of pointers to an integer:
int *ptr[MAX];
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to
an int value.
Following example makes use of three integers, which will be stored in an array of pointers as follows:
#include <stdio.h>
const int MAX =
3; int main ()
{
int var[] = {10, 100,
200}; int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to character to store a list of strings as follows:
#include <stdio.h>
const int MAX =
4; int main ()
{
char *names[] = {
"Zara Ali",
"Hina Ali",
―Nuha Ali",
"Sara
Ali", };
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
Output:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
NOTE: If you do not put the function within parenthesis, you will end up declaring a function returning a
pointer as shown:
int *func (int,int); /*function returning pointer to int*/
2. #include<stdio.h>
B. STRUCTURES
A structure is a collection of variables referenced under one name, providing a convenient
means of keeping related information together. A structure declaration forms a template that
can be used to create structure objects (that is, instances of a structure). The variables that make
up the structure are called members. (Structure members are also commonly referred to as
elements or fields.)
The general form of a structure declaration is
struct tag {
type member-name;
type member-name;
type member-name;
.
.
.
} structure-variables;
where either tag or structure-variables may be omitted, but not both.
For example, the name and address information in a mailing list would normally be represented
in a structure. The following code fragment shows how to declare a structure that defines the
name and address fields.
The keyword struct tells the compiler that a structure is being declared.
At this point, no variable has actually been created. Only the form of the data has been
defined. To declare a variable (that is, a physical object) of type addr, write
This declares a variable of type addr called addr_info. Thus, addr describes the form of a
structure (its type), and addr_info is an instance (an object) of the structure.
When a structure variable (addr_info) is declared, the compiler automatically
allocates Sufficient memory to accommodate all of its members.
You can also declare one or more objects when you declare a structure. For example,
#include <stdio.h>
struct addr{
char name[30];
char street[40];
char city[20];
char state[3];
};
main ()
{
struct addr addr_info; // creating the structure variable
struct addr binfo;
struct addr cinfo;
}
OR
For example, the following statement assigns the ZIP code 12345 to the zip field of the structure
variable addr_info declared earlier.
addr_info.zip = 12345;
PROGRAM:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming
Tutorial"); Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result:
#include<stdio.h>
main()
{
struct books b[3]; // creating array of structure variable
int i;
for(i=0;i<3;i++)
{
printf(―enter %d book record:‖, i+1);
printf(―enter book name:‖);
scanf(―%s‖,&b[i].title); // accessing structure member using “.” operator
printf(―enter book_id:‖);
scanf(―%d‖,&b[i].book_id); // accessing structure member using “.” operator
}
printf(―displaying book records \n‖);
for(i=0;i<3;i++)
{
printf(―book name is %s‖, b[i].title);
printf(―book_id is %d‖, b[i].book_id);
}
}
Output:
Enter the 1 book record
Enter book name: C programming
Enter book_id:1234
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
main()
{
struct student record;
record.id=1;
strcpy(record.name,‖john‖)
; record.percentage=87.5;
func(record);
}
void func(struct student record)
{
printf(―ID is %d \n‖,record.id);
printf(―Name is %s \n‖, record.name);
printf(―percentage is %f \n‖, record.percentage);
}
OUTPUT:
ID is 1
Name is john
Percentage is 87.5
Example:
#include<stdio.h>
#include<string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
main()
{
struct student record;
record.id=1;
strcpy(record.name,‖john‖)
; record.percentage=87.5;
func(&record);
}
void func(struct student *record)
{
printf(―ID is %d \n‖,record->id);
printf(―Name is %s \n‖, record->name);
printf(―percentage is %f \n‖, record->percentage);
}
OUTPUT:
ID is 1
Name is john
Percentage is 87.5
To access the members of a structure using a pointer to that structure, you must use the “–>”
operator.
The –>, usually called the arrow operator, consists of the minus sign followed by a greater than
sign. The arrow is used in place of the dot operator when you are accessing a structure member
through a pointer to the structure
Example:
#include<stdio.h>
#include<string.h>
struct student
{
int id;
char name[30];
};
main()
{
int i;
struct student
record={1,‖Raju‖,90.5}; struct
student *ptr;
ptr=&record;
printf(―record of student1: \n‖);
printf(―ID is : %d\n‖, ptr->id);
printf(―Name is: %s‖, ptr-
>name);
}
OUTPUT:
Record of student1
ID is 1
Name is Raju
C.UNION
A union is a memory location that is shared by two or more different types of variables. A union
provides a way of interpreting the same bit pattern in two or more different ways. Declaring a union
is similar to declaring a structure. A union is declared using union keyword.Its general form is
union tag
{
type member-name;
type member-name;
type member-name;
.
.
.
} union-variables;
For example:
union student
{
int i;
char ch;
};
This declaration does not create any variables.
Declaration of union variable
You can declare a variable either by placing its name at the end of the declaration or by using a separate
declaration statement. To declare a union variable called „s‟ of type student using the definition just
given, write
union student s;
Example:
union student{
int roll;
char name[4];
int marks;
};
Accessing UNION Members
Individual members of a structure are accessed through the use of the “.” operator (usually called the
dot operator).
The general form for accessing a member of a structure is,
object_name.member_name
For example, the following statement above declared ‗s‘ as a variable. So to access the union member
using variable as shown below;
s.roll;
s.name[];
s.marks;
Pointer to union
Pointer which stores address of union is called as pointer to union
Syntax:
Union team t1; // declaring union variable
Union team *ptr; // declaring union pointer variable
Ptr=&t1; // assigning address to union pointer.
Example:
#include<stdio.h>
union team
{
char name[10];
int member; char
caption[20];
};
int main()
{
union team t1,*ptr;
ptr=&t1;
t1.name=‖INDIA‖
;
printf(―Team:%s‖,
(*sptr).name);
printf(―Team:%s‖,sptr->name);
return 0;
}
OUTPUT:
Team:INDIA.
Team:INDIA.
All union members occupy ―same memory location‖ i,e; for the union, memory allocated will
be equal to the data memory with maximum size.
In the above example, if roll have size of 2 bytes and name have size of 4 bytes and marks has
2 bytes of size. Then the character array ―name‖ have max size thus ―maximum memory of
the union will be 4bytes‖.
Max memory of union= max memory of union data type
Unions are conceptually similar to structures.
The syntax of union is also similar to that of structure.
The only differences is in terms of storage. In structure each member has its own storage
location, whereas all members of union uses a single shared memory location which is equal to
the size of its largest data member.
This implies that although a union may contain many members of different types, it cannot handle all the members
at same time.
D.FILE HANDLINGS
Console oriented I/O- the term console here refers to the screen-keyboard pair. In console, the program
reads from the keyboard and writes onto the screen.
1. It becomes complicated and time consuming to handle huge amount of data through terminals
2. Data is lost when either the program is terminated or computer is turned off.
Therefore, it is necessary to store data on permanent storage device and read it whenever it is necessary
without losing data which can be done using files.
Files stores information for many purposes and retrieve whenever required by programs. A file
represents a sequence of bytes on a disk where a group of related data is stored.
Streams in C
Standard streams are termed as pre-connected i/p and o/p channels between the terminal and a program.
Therefore, Stream is a logical interface to the device that is connected to the computer.
3 standard streams
1. Standard input (stdin) - it is a stream from which the program receives the data.
2. Standard output (stdout) – it is a stream where the program writes its o/p data
3. Standard error (stderr) – iis basically an o/p stream used by the programs to report error
messages.
Types of file
It is also a stream o collection of bytes. In binary files, there is no constraint on a file it may be read
from or written to file in any manner (i.e., file is opened for any kind of operation at any given time). It
can be processed sequentially or randomly depending on the need of application.
Advantage
More efficient thantext files because of less memory space and no requirement for conversion from
internal to external.
Disadvantage
Contents of binary file is not human readable.
Processing a file
File Handling Functions For Reading And Writing into a File and Strings
1. Opening the File
While opening the file, the following are specified
Name of the file.
Manner in which mode it should be opened (reading, writing, appending, reading/writing).
The function ―fopen‖ is used to open a file. It accepts two arguments. The first is filename and second
is the mode in which it should be opened.
Syntax: FILE *fp=fopen(―filename‖,‖mode‖);
Example: FILE *fp;
fp=fopen(―x.txt‖, ―w‖) //the file x.txt is opened in write mode.
Mode Description
R opens a text file in reading mode
W opens a text file in writing mode
A opens a text file in appending mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both writing and reading mode
a+ opens a text file in both reading and writing mode
Rb opens a binary file in reading mode
Wb opens or create a binary file in writing mode
Ab opens a binary file in reading mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both writing and reading mode
ab+ opens a binary file in both reading and writing mode
2. Closing A File
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing t
he file. This EOF is a constant defined in the header file stdio.h.
Example:
Here is an example of opening and closing a file in write mode.
First, a file pointer fp is declared. Then fp is used to open a file named ―test.txt‖ in ‗w‘ mode, which
sta nds for write mode. If fp is null, it means that file could not be opened due to any error.
int main()
{
FILE *fp;
fp = fopen("test.txt","w");
if(fp==NULL)
{
printf("Error in opening file");
}
else
printf("File has been created
successfully"); fclose(fp);
}
3. Functions used for reading and writing a character into the file.
fgetc() and fputc()
fputc() writes a single character to the specified stream (or) outputs the value of character c to the
specified stream.
Syntax: int fputc(int character, FILE stream);
Where,
Character: The character to be writte ;p0gn in the file
stream: pointer to the file in which data will be written.
Return
Type: integer
Value: On success Integer value of the character which is written
On Failure EOF is returned, setting the error indicator.
A character is written in the position specified by the file pointer. After the write
of every character, file pointer increases by one and moves to the next position.
Example:
int main()
{
FILE * fp; //file pointer declaration
int len,i;
char buffer[20] = "Good morning"; //buffer is a string
len = strlen(buffer); //strlen is used to get length of buffer.
fp = fopen ("file.txt","w");
In this function, a string is defined at the beginning. After opening a file in write mode if successfully
opened, copy the string by one character after another. Here, fputc() is used to write the character in the
file.
fgetc()
It is used to read one by one character from file.
Syntax:
int fgetc ( FILE * stream );
Parameters
stream: Pointer to the file from which data will be read.
Return
type:
It returns the character which is currently pointed by the FILE pointer.
Example:
#include<stdio.h>
int main()
{
FILE * fp;
int count =
0; char ch;
fp = fopen ("file.txt","r");
if (fp == NULL) printf ("Error in opening file");
else {
while((ch = fgetc(fp)) !=
EOF) count++;
}
Advanced Computer Programming UNIT 1 Page 30
Vidya Murugendrappa
Assistant Professor
Here, a file is opened in read mode. Then until the end of file, characters are read from the file (with
punctuation and space) using fgetc() and count of characters are increased. When it reaches EOF, total
number of character is printed on the screen.
4. Functions used for reading and writing the strings into the file.
fputs() and fgets()
fputs()
It is used to write the string in file.
Prototype:
int fputs(const char* str, FILE* stream );
Parameters
str:- constant character pointer or string that is to be written in the file. stream:- pointer to the file in
which the data is to be written.
Return
Type: integer
Value: On success Non negative value and
On failure: End of file(EOF), setting the error indicator
fgets()
fgets is used to read data from
file. Prototype:
char* fgets(char* str,int count,FILE* stream);
Parameters
str: character pointer that will point to the returned data from file.
count: integer that is the maximum count of character to return from the file. If the number is n, then (n-
1) character is returned from the file. If the number of characters is less than n-1, then full data from the
file will be returned.
stream: pointer to the file from which the data will be fetch
Return:
Type: character pointer(char*)
Value: On success String which is read
On failure Null pointer, setting the error indicator
int main()
{
FILE* fp;
char ch[20];
fp = fopen("testFile.txt","w");
if(fp == NULL)
printf("Error in creating
file"); else
fputs("This is a test
file",fp); fclose(fp);
fp = fopen("testFile.txt","r");
if(fp == NULL)
{
printf("Error in opening file");
}
else
{
fgets(ch,20,fp);
printf("\n%s",ch);
}
getch();
return 0;
}
In this example, a file is opened in write mode. After successful opening, a string is put in the file using
fputs() function. The file is then closed and again opened in read mode. Next using fgets() function,
twenty characters are read from starting position of the file and printed it on the console.
Parameters
stream: pointer to the file in which the data is to be written.
str: character pointer to the data to be written, which can include the format of the data.
Return
Type: integer
Value: On success number of characters which is written
On Failure Negative number.
fscanf(): It works like scanf() function, with some differences. While scanf() works for standard input,
fscanf() is for file reading.
Parameters
stream: pointer to the file from which the data is to be read.
str: character pointer to the data to be read. It is mainly the format of the data.
Advanced Computer Programming UNIT 1 Page 33
Vidya Murugendrappa
Assistant Professor
Return
Type: integer
Value: On success number of arguments which is filled
On failure error indicator is set and EOF is returned.
Example:
#include<stdio.h>
Struct emp
{
char name[10];
int age;
}
void main()
{
struct emp e;
FILE *p,*q;
p=fopen(―one.txt‖,‖a‖);
q=fopen(―one.txt‖,‖r‖);
printf(―enter name and age: ―);
scanf(―%s %d‖,
e.name,&e.age); fprintf(p,‖%s
%d‖, e.name,e.age); fclose(p);
do
{
fscanf(q, ―%s %d‖, e.name,
&e.age); printf(―%s %d‖, e.name,
e.age);
}
while(!feof(q));
Advanced Computer Programming UNIT 1 Page 34
Vidya Murugendrappa
Assistant Professor
fclose(q);
return 0;
}
In the above program, we have declared emp structure with members name and age. We have declared
two file pointers p to open file in append mode and q in read mode and structure variable ―e‖ of
employee (emp) structure. Using fprintf and fscanf we write the data into file and read the data from
file.
6. fseek()
It is used to set file pointer to any position.
Prototype is:
int fseek ( FILE * stream, long int offset, int origin );
Parameters
Stream: pointer to a file.
Offset: Number of bytes or characters from the origin.
Origin: The original position is set here. From this position, using the offset, the file pointer is set to a
new position. Generally, three positions are used as origin:
Return
Type: Integer
Value: On success Zero (0)
On failure Non-Zero
Example:
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen(―file.txt‖,‖w‖
); if(fp==NULL)
printf(―error in opening
file‖); else
{
Using SEEK_SET and offset, the word France is replaced by Brazil. Then by using SEEK_CUR, and
position is appended with the string(and Portugal).
Parameters:
ptr: pointer to the data which will be stored.
size: the size of data elements (in byte) to be written.
Return
Type: size_t
Value: On success number of elements which are successfully written
On failure zero (0) if the size or count is 0. Error indicator is set.
fread()
It is used to read data from file. Prototype of the function is:
Parameters
ptr: pointer to memory where the read data will be
stored. size: size of data elements (in byte) to be read.
count: number of data elements to be read.
stream: pointer to the file from which the data will be read.
Return
Type: size_t
Value: On success number of elements which are successfully read.
On failure returns zero (0) if the size or count is 0, Error indicator is set.
Example:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[] = "this is reva university";
char buffer[100];
return(0);
}
8. ftell()
It is used to get current position of the file pointer. The function prototype is:
Parameters
stream: Pointer to a file.
Return
Type: long integer.
Value: On success value of current position or offset bytes
On failure -1. System specific error no is set
Example:
int main () {
FILE * fp;
long int len;
fp = fopen ("file.txt","r");
if (fp==NULL)
printf ("Error in opening
file"); else {
fseek (fp, 0, SEEK_END);
len=ftell (fp);
}
fclose (fp);
printf ("The file contains %ld characters.\n",len);
}
In this example, file.txt is opened and using fseek(), file pointer is set to the end of the file. Then, ftell()
is used to get the current position, i.e. offset from the beginning of the file.
9. Rewind()
It is used to set the file pointer at the beginning of the file. Function prototype:
Parameters
stream: Pointer to a file.
In any stage of the program, if we need to go back to the starting point of the file, we can use rewind()
and send the file pointer as the parameter.
Example:
#include<stdio.h>
int main ()
{
int n;
FILE * fp;
fp = fopen ("file.txt","w+");
if (fp==NULL)
printf ("Error in opening
file"); else {
fputs ("France is my favorite
team",fp); rewind (fp);
fputs("Brazil",fp);
}
fclose (fp);
}
In the above example, first, some string is written in the file. Then rewind() is used to set the file pointer
at the beginning of the file. Then overwrite a word.
10. feof()
It is used to check whether end of file for a stream is set or not. Prototype is:
Parameters
stream - Pointer to a file.
Return
Type: integer
Value: Non zero value if EOF is set for the stream Zero Otherwise.
by using file pointer as a parameter of feof(), we can check whether end of file has been reached or not.
Example:
#include<stdio.h>
int main()
{
FILE *p;
int c;
fp=fopen(―file.txt‖,‖r‖);
if(fp==NULL)
{
printf(―/nerror in opeing the
file‖); return 0;
}
while(1)
{
c=fgetc(fp);
if (feof(fp))
break;
printf(―%c‖,c);
}
fclose(fp);
return 0;
}
In the above program file.txt file is opened in read mode. Using fgetc() reads a character from the file.
The statement ―feof(fp)‖ checks whether end of file is reached or not. If it has reached it comes out of
the file or else it reads the character from the file.
E. APPLICATIONS OF DATA STRUCTURES
Manipulate hierarchical data.
Make information easy to search (see tree traversal).
Manipulate sorted lists of data.
As a workflow for compositing digital images for visual effects.
int main()
{
FILE *fp;
char ch;
return(0);
}
Other problems on structures.