1
 An Array is a collection of variables of the
same type that are referred to through a
common name.
 Declaration
type var_name[size]
e.g
2
int A[6];
double d[15];
After declaration, array contains some garbage
value.
Static initialization
Run time initialization
3
int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int i;
int A[6];
for(i = 0; i < 6; i++)
A[i] = 6 - i;
int A[6];
6 elements of 4 bytes each,
total size = 6 x 4 bytes = 24 bytes
Read an element
Write to an element
{program: array_average.c}
4
A[0] A[1] A[2] A[3] A[4] A[5]
0x1000 0x1004 0x1008 0x1012 0x1016 0x1020
6 5 4 3 2 1
int tmp = A[2];
A[3] = 5;
 No “Strings” keyword
 A string is an array of characters.
OR
5
char string[] = “hello world”;
char *string = “hello world”;
• Compiler has to know where the string ends
• ‘0’ denotes the end of string
{program: hello.c}
Some more characters (do $man ascii):
‘n’ = new line, ‘t’ = horizontal tab, ‘v’ =
vertical tab, ‘r’ = carriage return
‘A’ = 0x41, ‘a’ = 0x61, ‘0’ = 0x00
6
char string[] = “hello world”;
printf(“%s”, string);
 aggregate in that they hold multiple data items at
one time
 named members hold data items of various types
 like the notion of class/field in C or C++
– but without the data hiding features
 scalar in that C treats each structure as a unit
 as opposed to the “array” approach: a pointer to a
collection of members in memory
 entire structures (not just pointers to structures) may be
passed as function arguments, assigned to variables,
etc.
 Interestingly, they cannot be compared using ==
(rationale: too inefficient)
7
 Combined variable and type declaration
struct tag {member-list} variable-list;
 Any one of the three portions can be omitted
struct {int a, b; char *p;} x, y; /* omit tag */
 variables x, y declared with members as described:
int members a, b and char pointer p.
 x and y have same type, but differ from all others –
even if there is another declaration:
struct {int a, b; char *p;} z;
/* z has different type from x, y */
8
struct S {int a, b; char *p;}; /* omit variables */
 No variables are declared, but there is now a type
struct S that can be referred to later
struct S z; /* omit members */
 Given an earlier declaration of struct S, this declares a
variable of that type
typedef struct {int a, b; char *p;} S;
/* omit both tag and variables */
 This creates a simple type name S
(more convenient than struct S)
9
 Direct access operator s.m
 subscript and dot operators have same precedence and
associate left-to-right, so we don’t need parentheses for
sam.pets[0].species
 Indirect access s->m: equivalent to (*s).m
 Dereference a pointer to a structure, then return a
member of that structure
 Dot operator has higher precedence than indirection
operator , so parentheses are needed in (*s).m
(*fido.owner).name or fido.owner->name
10
. evaluated first: access owner member
* evaluated next: dereference pointer to
HUMAN
. and -> have equal precedence
and associate left-to-right
 Portability is an issue:
 Do any bit field sizes exceed the machine’s int size?
 Is there any pointer manipulation in your code that
assumes a particular layout?
 Bit fields are “syntactic sugar” for more complex
shifting/masking
 e.g. to get font value, mask off the ch and size bits,
then shift right by 19
 This is what actually happens in the object code –
bit fields just make it look simpler at the source level
11
 Structures are scalars, so they can be returned and
passed as arguments – just like ints, chars
struct BIG changestruct(struct BIG s);
 Call by value: temporary copy of structure is created
 Caution: passing large structures is inefficient
– involves a lot of copying
 avoid by passing a pointer to the structure instead:
void changestruct(struct BIG *s);
 What if the struct argument is read-only?
 Safe approach: use const
void changestruct(struct BIG const *s);
12
 Like structures, but every member occupies the
same region of memory!
 Structures: members are “and”ed together: “name and
species and owner”
 Unions: members are “xor”ed together
union VALUE {
float f;
int i;
char *s;
};
/* either a float xor an int xor a string */
13
 Up to programmer to determine how to interpret a
union (i.e. which member to access)
 Often used in conjunction with a “type” variable
that indicates how to interpret the union value
enum TYPE { INT, FLOAT, STRING };
struct VARIABLE {
enum TYPE type;
union VALUE value;
};
14
Access type to determine
how to interpret value
 Storage
 size of union is the size of its largest member
 avoid unions with widely varying member sizes;
for the larger data types, consider using pointers instead
 Initialization
 Union may only be initialized to a value appropriate for
the type of its first member
15
 File – place on disc where group of related
data is stored
 E.g. your C programs, executables
 High-level programming languages support
file operations
 Naming
 Opening
 Reading
 Writing
 Closing
 fp
 contains all information about file
 Communication link between system and program
 Mode can be
 r open file for reading only
 w open file for writing only
 a open file for appending (adding) data
FILE *fp; /*variable fp is pointer to type FILE*/
fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */
 Writing mode
 if file already exists then contents are deleted,
 else new file with specified name created
 Appending mode
 if file already exists then file opened with contents safe
 else new file created
 Reading mode
 if file already exists then opened with contents safe
 else error occurs.
FILE *p1, *p2;
p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
 r+ open to beginning for both
reading/writing
 w+ same as w except both for reading and
writing
 a+ same as ‘a’ except both for reading and
writing
 File must be closed as soon as all operations on it completed
 Ensures
 All outstanding information associated with file flushed out from
buffers
 All links to file broken
 Accidental misuse of file prevented
 If want to change mode of file, then first close and open
again
Syntax: fclose(file_pointer);
Example:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);
 C provides several different functions for
reading/writing
 getc() – read a character
 putc() – write a character
 fprintf() – write set of data values
 fscanf() – read set of data values
 getw() – read integer
 putw() – write integer
 handle one character at a time like getchar() and
putchar()
 syntax: putc(c,fp1);
 c : a character variable
 fp1 : pointer to file opened with mode w
 syntax: c = getc(fp2);
 c : a character variable
 fp2 : pointer to file opened with mode r
 file pointer moves by one character position after every
getc() and putc()
 getc() returns end-of-file marker EOF when file end
reached
#include <stdio.h>
main()
{ FILE *fp1;
char c;
f1= fopen(“INPUT”, “w”); /* open file for writing */
while((c=getchar()) != EOF) /*get char from keyboard
until CTL-Z*/
putc(c,f1); /*write a
character to INPUT */
fclose(f1); /* close INPUT
*/
f1=fopen(“INPUT”, “r”); /* reopen file */
while((c=getc(f1))!=EOF) /*read character from file INPUT*/
printf(“%c”, c); /* print character to
screen */
fclose(f1);
} /*end main */
• similar to scanf() and printf()
• in addition provide file-pointer
• given the following
– file-pointer f1 (points to file opened in write mode)
– file-pointer f2 (points to file opened in read mode)
– integer variable i
– float variable f
• Example:
fprintf(f1, “%d %fn”, i, f);
fprintf(stdout, “%f n”, f); /*note: stdout refers to
screen */
fscanf(f2, “%d %f”, &i, &f);
• fscanf returns EOF when end-of-file reached
 handle one integer at a time
 syntax: putw(i,fp1);
 i : an integer variable
 fp1 : pointer to file ipened with mode w
 syntax: i = getw(fp2);
 i : an integer variable
 fp2 : pointer to file opened with mode r
 file pointer moves by one integer position, data
stored in binary format native to local system
 getw() returns end-of-file marker EOF when file end
reached
 Typical errors that occur
 trying to read beyond end-of-file
 trying to use a file that has not been opened
 perform operation on file not permitted by
‘fopen’ mode
 open file with invalid filename
 write to write-protected file
 given file-pointer, check if EOF reached, errors
while handling file, problems opening file etc.
 check if EOF reached: feof()
 feof() takes file-pointer as input, returns nonzero if
all data read and zero otherwise
if(feof(fp))
printf(“End of datan”);
 ferror() takes file-pointer as input, returns nonzero
integer if error detected else returns zero
if(ferror(fp) !=0)
printf(“An error has occurredn”);
 if file cannot be opened then fopen returns a
NULL pointer
 Good practice to check if pointer is NULL
before proceeding
fp = fopen(“input.dat”, “r”);
if (fp == NULL)
printf(“File could not be opened n ”);
 how to jump to a given position (byte number) in a
file without reading all the previous data?
 fseek (file-pointer, offset, position);
 position: 0 (beginning), 1 (current), 2 (end)
 offset: number of locations to move from position
Example: fseek(fp,-m, 1); /* move back by m bytes from
current
position */
fseek(fp,m,0); /* move to (m+1)th byte in file
*/
fseek(fp, -10, 2); /* what is this? */
 ftell(fp) returns current byte position in file
 rewind(fp) resets position to start of file
 can give input to C program from command line
E.g. > prog.c 10
name1 name2 ….
 how to use these arguments?
main ( int argc, char *argv[] )
 argc – gives a count of number of arguments
(including program name)
 char *argv[] defines an array of pointers to
character (or array of strings)
 argv[0] – program name
 argv[1] to argv[argc -1] give the other arguments
as strings

Programming in C

  • 1.
  • 2.
     An Arrayis a collection of variables of the same type that are referred to through a common name.  Declaration type var_name[size] e.g 2 int A[6]; double d[15];
  • 3.
    After declaration, arraycontains some garbage value. Static initialization Run time initialization 3 int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int i; int A[6]; for(i = 0; i < 6; i++) A[i] = 6 - i;
  • 4.
    int A[6]; 6 elementsof 4 bytes each, total size = 6 x 4 bytes = 24 bytes Read an element Write to an element {program: array_average.c} 4 A[0] A[1] A[2] A[3] A[4] A[5] 0x1000 0x1004 0x1008 0x1012 0x1016 0x1020 6 5 4 3 2 1 int tmp = A[2]; A[3] = 5;
  • 5.
     No “Strings”keyword  A string is an array of characters. OR 5 char string[] = “hello world”; char *string = “hello world”;
  • 6.
    • Compiler hasto know where the string ends • ‘0’ denotes the end of string {program: hello.c} Some more characters (do $man ascii): ‘n’ = new line, ‘t’ = horizontal tab, ‘v’ = vertical tab, ‘r’ = carriage return ‘A’ = 0x41, ‘a’ = 0x61, ‘0’ = 0x00 6 char string[] = “hello world”; printf(“%s”, string);
  • 7.
     aggregate inthat they hold multiple data items at one time  named members hold data items of various types  like the notion of class/field in C or C++ – but without the data hiding features  scalar in that C treats each structure as a unit  as opposed to the “array” approach: a pointer to a collection of members in memory  entire structures (not just pointers to structures) may be passed as function arguments, assigned to variables, etc.  Interestingly, they cannot be compared using == (rationale: too inefficient) 7
  • 8.
     Combined variableand type declaration struct tag {member-list} variable-list;  Any one of the three portions can be omitted struct {int a, b; char *p;} x, y; /* omit tag */  variables x, y declared with members as described: int members a, b and char pointer p.  x and y have same type, but differ from all others – even if there is another declaration: struct {int a, b; char *p;} z; /* z has different type from x, y */ 8
  • 9.
    struct S {inta, b; char *p;}; /* omit variables */  No variables are declared, but there is now a type struct S that can be referred to later struct S z; /* omit members */  Given an earlier declaration of struct S, this declares a variable of that type typedef struct {int a, b; char *p;} S; /* omit both tag and variables */  This creates a simple type name S (more convenient than struct S) 9
  • 10.
     Direct accessoperator s.m  subscript and dot operators have same precedence and associate left-to-right, so we don’t need parentheses for sam.pets[0].species  Indirect access s->m: equivalent to (*s).m  Dereference a pointer to a structure, then return a member of that structure  Dot operator has higher precedence than indirection operator , so parentheses are needed in (*s).m (*fido.owner).name or fido.owner->name 10 . evaluated first: access owner member * evaluated next: dereference pointer to HUMAN . and -> have equal precedence and associate left-to-right
  • 11.
     Portability isan issue:  Do any bit field sizes exceed the machine’s int size?  Is there any pointer manipulation in your code that assumes a particular layout?  Bit fields are “syntactic sugar” for more complex shifting/masking  e.g. to get font value, mask off the ch and size bits, then shift right by 19  This is what actually happens in the object code – bit fields just make it look simpler at the source level 11
  • 12.
     Structures arescalars, so they can be returned and passed as arguments – just like ints, chars struct BIG changestruct(struct BIG s);  Call by value: temporary copy of structure is created  Caution: passing large structures is inefficient – involves a lot of copying  avoid by passing a pointer to the structure instead: void changestruct(struct BIG *s);  What if the struct argument is read-only?  Safe approach: use const void changestruct(struct BIG const *s); 12
  • 13.
     Like structures,but every member occupies the same region of memory!  Structures: members are “and”ed together: “name and species and owner”  Unions: members are “xor”ed together union VALUE { float f; int i; char *s; }; /* either a float xor an int xor a string */ 13
  • 14.
     Up toprogrammer to determine how to interpret a union (i.e. which member to access)  Often used in conjunction with a “type” variable that indicates how to interpret the union value enum TYPE { INT, FLOAT, STRING }; struct VARIABLE { enum TYPE type; union VALUE value; }; 14 Access type to determine how to interpret value
  • 15.
     Storage  sizeof union is the size of its largest member  avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead  Initialization  Union may only be initialized to a value appropriate for the type of its first member 15
  • 16.
     File –place on disc where group of related data is stored  E.g. your C programs, executables  High-level programming languages support file operations  Naming  Opening  Reading  Writing  Closing
  • 17.
     fp  containsall information about file  Communication link between system and program  Mode can be  r open file for reading only  w open file for writing only  a open file for appending (adding) data FILE *fp; /*variable fp is pointer to type FILE*/ fp = fopen(“filename”, “mode”); /*opens file with name filename , assigns identifier to fp */
  • 18.
     Writing mode if file already exists then contents are deleted,  else new file with specified name created  Appending mode  if file already exists then file opened with contents safe  else new file created  Reading mode  if file already exists then opened with contents safe  else error occurs. FILE *p1, *p2; p1 = fopen(“data”,”r”); p2= fopen(“results”, w”);
  • 19.
     r+ opento beginning for both reading/writing  w+ same as w except both for reading and writing  a+ same as ‘a’ except both for reading and writing
  • 20.
     File mustbe closed as soon as all operations on it completed  Ensures  All outstanding information associated with file flushed out from buffers  All links to file broken  Accidental misuse of file prevented  If want to change mode of file, then first close and open again Syntax: fclose(file_pointer); Example: FILE *p1, *p2; p1 = fopen(“INPUT.txt”, “r”); p2 =fopen(“OUTPUT.txt”, “w”); …….. …….. fclose(p1); fclose(p2);
  • 21.
     C providesseveral different functions for reading/writing  getc() – read a character  putc() – write a character  fprintf() – write set of data values  fscanf() – read set of data values  getw() – read integer  putw() – write integer
  • 22.
     handle onecharacter at a time like getchar() and putchar()  syntax: putc(c,fp1);  c : a character variable  fp1 : pointer to file opened with mode w  syntax: c = getc(fp2);  c : a character variable  fp2 : pointer to file opened with mode r  file pointer moves by one character position after every getc() and putc()  getc() returns end-of-file marker EOF when file end reached
  • 23.
    #include <stdio.h> main() { FILE*fp1; char c; f1= fopen(“INPUT”, “w”); /* open file for writing */ while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/ putc(c,f1); /*write a character to INPUT */ fclose(f1); /* close INPUT */ f1=fopen(“INPUT”, “r”); /* reopen file */ while((c=getc(f1))!=EOF) /*read character from file INPUT*/ printf(“%c”, c); /* print character to screen */ fclose(f1); } /*end main */
  • 24.
    • similar toscanf() and printf() • in addition provide file-pointer • given the following – file-pointer f1 (points to file opened in write mode) – file-pointer f2 (points to file opened in read mode) – integer variable i – float variable f • Example: fprintf(f1, “%d %fn”, i, f); fprintf(stdout, “%f n”, f); /*note: stdout refers to screen */ fscanf(f2, “%d %f”, &i, &f); • fscanf returns EOF when end-of-file reached
  • 25.
     handle oneinteger at a time  syntax: putw(i,fp1);  i : an integer variable  fp1 : pointer to file ipened with mode w  syntax: i = getw(fp2);  i : an integer variable  fp2 : pointer to file opened with mode r  file pointer moves by one integer position, data stored in binary format native to local system  getw() returns end-of-file marker EOF when file end reached
  • 26.
     Typical errorsthat occur  trying to read beyond end-of-file  trying to use a file that has not been opened  perform operation on file not permitted by ‘fopen’ mode  open file with invalid filename  write to write-protected file
  • 27.
     given file-pointer,check if EOF reached, errors while handling file, problems opening file etc.  check if EOF reached: feof()  feof() takes file-pointer as input, returns nonzero if all data read and zero otherwise if(feof(fp)) printf(“End of datan”);  ferror() takes file-pointer as input, returns nonzero integer if error detected else returns zero if(ferror(fp) !=0) printf(“An error has occurredn”);
  • 28.
     if filecannot be opened then fopen returns a NULL pointer  Good practice to check if pointer is NULL before proceeding fp = fopen(“input.dat”, “r”); if (fp == NULL) printf(“File could not be opened n ”);
  • 29.
     how tojump to a given position (byte number) in a file without reading all the previous data?  fseek (file-pointer, offset, position);  position: 0 (beginning), 1 (current), 2 (end)  offset: number of locations to move from position Example: fseek(fp,-m, 1); /* move back by m bytes from current position */ fseek(fp,m,0); /* move to (m+1)th byte in file */ fseek(fp, -10, 2); /* what is this? */  ftell(fp) returns current byte position in file  rewind(fp) resets position to start of file
  • 30.
     can giveinput to C program from command line E.g. > prog.c 10 name1 name2 ….  how to use these arguments? main ( int argc, char *argv[] )  argc – gives a count of number of arguments (including program name)  char *argv[] defines an array of pointers to character (or array of strings)  argv[0] – program name  argv[1] to argv[argc -1] give the other arguments as strings