Sunteți pe pagina 1din 19

Structures.

• Used to Lump Together –collections of different variable types --


- so that they can be conveniently treated as an unit.
struct ship /* The word "ship" is the structure's "tag". */
{
char name[30];
double displacement; /* in grammes */
float length_of_water_line; /* in meters */
unsigned short int number_of_passengers;
unsigned short int number_of_crew;
};

To use this structure we can declare


struct ship viraat, vikrant, western_fleet[100];
viraat.displacement = 97500000000.0;
viraat.length_of_water_line = 750.0
viraat.number_of_passengers = 3575;
viraat.number_of_crew = 4592;
Another Example :
Struct date
{ int month;
int day;
int year;}
Struct officer_particulars
{ char name[30];
int service_no;
char course[20];
struct date date_of_comm;
struct date date_of_birth;}
aftc[200];
USE : aftc[23].date_of_comm.month = 18;
aftc[181].service_no = 23456;
Structures – Example & problems
Example --- struct1.cpp
1 – define a structure – of tag student with members as char name[25], state[30]
, int service no and age – int. assign this tag to 3 students tom , dick and harry.
Input relevant data and print them out on screen
2 – Define a structure tag date with members dat, month and year of type int.
Now define a structure of type student_data which contain members name[25],
service_no (int), check suffix (char), date_of_comm and date_of_birth – as
substructures of type date. Assign this structure to an array of students[5]. Input
relevant data, and print out as a formatted output including a column for
age_on_commissioning. ( to be computed – by a function)

Name Service No Chk Suffix Date of Birth Date Of Comm Age on Comm’n
POINTERS
• Pointer in C is the address of Something
• It is a variable that holds tha address of something

Pointers are memory cells which contain the


address of a data element.
The variable name is preceeded by a * character.
To reserve an element of type char and a pointer
to an element of type char
char c;
char *ch_p;
The companion unary operator '&' which yields the
address of the variable. So to initialize our
pointer ch_p to point at the char c,
ch_p = &c;
float x;
float* px;
x = 6.5; px = &x;
defines px to be a pointer to objects of type float, and sets it
equal to the address of x:

Pointer use for a variable


The content of the memory location referenced by a pointer is
obtained using the ``*'' operator (this is called dereferencing the
pointer). Thus, *px refers to the value of x.
• C allows us to perform arithmetic operations using
pointers, but beware that the ``unit'' in pointer arithmetic
is the size (in bytes) of the object to which the pointer
points.
• For example, if px is a pointer to a variable x of type float,
then the expression px + 1 refers not to the next bit or byte
in memory but to the location of the next float after x (4
bytes away on most workstations)
• if x were of type double, then px + 1 would refer to a
location 8 bytes (the size of a double)away, and so on.
• Only if x is of type char will px + 1 actually refer to the
next byte in memory.
• Arrays of any type can be formed in C.
• The elements of the array occupy adjacent locations in memory.
• C treats the name of the array as if it were a pointer to the first
element
• This is important in understanding how to do arithmetic with
arrays.
•Thus, if v is an array, *v is the same thing as v[0], *(v+1) is the
same thing as v[1], and so on:
ARRAYS AND POINTERS

Let student[k] be an array and k is an int variable


Then
• student[6]
• *(student + 6)
• *(&student[0] + 6)
All mean the same thing
They access the 6th element of the array student
Array name – without index –interpreted as a pointer
constant pointing to the first element of array
Arrays & Pointers - Exercises
• ptrs1.cpp -- demo
• ptrs7.c ---- return multiple values from function
using pointers demo

• Ex 3 -- declare an array to hold 10 ints. Input 10


integers , assign the base address of the array to a
pointer variable and print out both the address location
and the array contents by incrementing the pointer
Ex 4 – try the same with 10 characters. What do u infer
from the results ?
Ex 5 – input 10 characters into an array A[10] and get
the reversed string into B[10] using pointers. Print
A[10] and B[10].
Arrays and Pointers.
struct ship /* The word "ship" is the structure's "tag". */
{
char name[30];
double displacement; /* in grammes */
float length_of_water_line; /* in meters */
unsigned short int number_of_passengers;
unsigned short int number_of_crew;
};
struct ship *vessel_p;
Note the use of the suffix "_p".
This is one way of reminding yourself that the
variable is a pointer.
struct ship fleet[5]; /* This allocates
enough storage for 5 ships' info. */
Now set the pointer to point at the first vessel
in the fleet.
vessel_p = fleet;
This pointer can be made to point at other ships
in the fleet by incrementing it or doing additive
arithmetic on it:
vessel_p++; /* point a the next ship */
vessel_p = fleet + 3;
Also we can find out the index of the ship in the
fleet at which we are pointing:
i = vessel_p - fleet;
Separation of two pointers pointing at elements
in an array:
d = vessel_p - another_vessel_p;/* This gives the
separation in elements. */
So summarising, pointers may be, incremented,
decremented, and subtracted one from another or
have a constant subtracted from them. Any other
mathematical operation is meaningless and not
allowed.
• When the arithmetic is done using pointers the
result is ALWAYS expressed in elements rather
than bytes.
• When using a pointer to reference a structure
we have to use a "pointer offset" operator in
order to access the member of the struct we
require:
vessel_p = fleet;
vessel_p->name = "Queen Mary";
vessel_p->displacement = 97500000000.0;
vessel_p->length_of_water_line = 750.0
vessel_p->number_of_passengers = 3575;
vessel_p->number_of_crew = 4592;
Remember:
• It's a “.” when accessing a struct which
is in storage declared in the program.
• It's a "->" when accessing a struct at
which a pointer is pointing.
Exercises

Ex- 6 – rewrite the program of Ex –2 to


incorporate data entry and display – through
pointers.
FILE INPUT OUTPUT
Statements exist for handling I/O to and from files. They are
#include < stdio.h>
FILE *fp;
fp = fopen(name, mode);
fscanf(fp, "format string", variable list);
fprintf(fp, "format string", variable list);
fclose(fp );
The logic here is that the code must
 define a local ``pointer'' of type FILE (uppercase is
necessary here), which is defined in < stdio.h>
 ``open'' the file and associate it with the local pointer via
fopen
 perform the I/O operations using fscanf and fprintf
 disconnect the file from the task with fclose
The ``mode'' argument in the fopen specifies the
purpose/positioning in opening the file:
``r'' for reading,
``w'' for writing, and
``a'' for appending to the file.

#include < stdio.h>


void main()
{ FILE *fp;
int i;
fp = fopen("foo.dat", "w"); /* open foo.dat for writing */
fprintf(fp, "\nSample Code\n\n"); /* write some info */
for (i = 1; i <= 10 ; i++)
fprintf(fp, "i = %d\n", i);
fclose(fp); /* close the file */
}
• The standard library used in conjunction with
"stdio.h" provides some quite useful facilities
for handling files.
• All file handling is done via objects of type
pointer to FILE. This compound data type is
defined in "stdio.h".
• The following file handling functions are
provided in the standard library.

fopen() Open a file


fclose() Close a file
fprintf() Formatted writeto a file
fscanf() Formatted read from a file
fputc() Write a character to a file
fgetc() Read a character from a file
fputs() Write a string to a file
fgets() Read a string from a file
putc() Write a character to a file
getc() Read a character from a file
ungetc() Un-read a character from a file
fread() Unformatted read from a file
fwrite() Unformatted write to a file
fgetpos() get current position in a file
fseek() Adjust current position in a file
fsetpos() Set current positionin a file
ftell() Determine current position in file
rewind() Set position to start of file
feof() Whether end-of-file has been seen
ferror() Tests whether afile error has
occurred
clearerr()Clears file error indicator
remove() Delete a file
rename() Rename a file
tmpfile() Create a temporary file
tmpnam() Create a uniquefile name
fflush() Force writing of data from buffer
to file
freopen() Opens a file using a specific
FILE object

There are also a number of pre-defined constants


in "stdio.h" which are useful during file
operations.

FOPEN_MAX Maximum number of open files


FILENAME_MAX Maximum length of file name
SEEK_CUR Used with fseek() function
SEEK_END Used with fseek() function
SEEK_SET Used with fseek() function
stderr Pre-opened file
stdout Pre-opened file
stdin Pre-opened file
Exercises
Demo – files2.cpp --to get input and print it to a file
Ex – 7 – Write a program to accept a filename and printout the
contents of the file on the screen.
Ex –8 Write a program to accept input 10 strings from keyboard,
store them in a file. The program should then sort the strings
based on the first character and write the sorted list to another
file.
Ex –9 Write a program to read the contents of a file ,invert every
byte and write it to another file.
Ex – 10 – write a prog to read the file created by Ex –9 and get
back the original.

S-ar putea să vă placă și