1 tdba66 lecture ch9 vt-03 type declaration possible to create user defined data types used to give...

25
1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data type type_name; typedef unsigned int PosInt; ... PosInt randomNumber;

Post on 20-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

1TDBA66 Lecture Ch9 vt-03

Type declaration

Possible to create user defined data types

Used to give special names for a certain data type

typedef data type type_name;

typedef unsigned int PosInt;

...

PosInt randomNumber;

Page 2: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

2TDBA66 Lecture Ch9 vt-03

example...typedef double ** MatrixType;

void writeMatrix(MatrixType matrix, int m, int n); /* prototype */

void main(void){ MatrixType a;

int i,j; a = (double *) calloc(4,sizeof(double *));

for (i=0;i<4;i++) a[i] = (double *) calloc(3,sizeof(double));

srand(time(NULL)); /* random seed */

for (i=0;i<4;i++) for (j=0;j<3;j++) a[i][j] = rand()%100 - 50.0;

writeMatrix(a,4,3); }/* main */...

Prototype

Page 3: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

3TDBA66 Lecture Ch9 vt-03

Data structures

• We have used arrays where every element of the same data type

• assemble information of different data types in one unit (a record)

• Example: you want to organize your books

• One book is described by

o Titleo Authoro Year publishedo If borrowed, by whomo Publishero …

Page 4: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

4TDBA66 Lecture Ch9 vt-03

New data structure in C- struct

struct tagname

{

members /* of different data types */

};

• Variables can now be declared

struct tagname var1,var2,var3;

• tagname may be omitted - but in that case you have not created a new data type name that can be used to declare variables

Page 5: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

5TDBA66 Lecture Ch9 vt-03

Bok

struct Book { char *title; int publishedYear; char *author; };

• struct Book can be used to declare variables

struct Book b;

Page 6: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

6TDBA66 Lecture Ch9 vt-03

Book – without tagname

struct { char *title; int publishedYear; char *author; }b1,b2,b3;

• b1, b2 and b3 variables of type above (Book)

• No further variables can be declared (unless repeating)

• Impossible for parameter declaration

Page 7: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

7TDBA66 Lecture Ch9 vt-03

The members

• To access a certain member in a variable of type struct one uses dot notation struct_variable.member

• a member can be treated like a single variable of the same data type

b.title = "Bilbo - en hobbits äventyr"; b.author = "J.J.R. Tolkien"; b.publishedYear = 1935;

• A variable of type struct can be assigned the value of an other variable of the same struct

Book b, otherBook;/* b gets values as above */

otherBook = b; /* all information is copied */

Page 8: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

8TDBA66 Lecture Ch9 vt-03

Example Book#include <stdio.h>

typedef struct { char *title; int publishedYear; char *author; } Book;

int main(void){ Book b; /* not needed !!!!!!!!!b.title =

malloc(25*sizeof(char)); b.author = malloc(25*sizeof(char));*/

b.title = "Bilbo - en hobbits äventyr"; b.author = "J.J.R. Tolkien"; b.publishedYear= 1935; printf("Title : %s \n",b.title); printf("Author: %s \n",b.author); printf("Published: %d\n",b.publishedYear);

return 0;}/* main */

Page 9: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

9TDBA66 Lecture Ch9 vt-03

Pointers & structures

• Pointer to struct is, of course, useful when a struct is an output parameter from a function

• Ex. Book *p;

*p is the struct that p points at

• In the Book-example

int main(void){ Book *p; (*p).title = malloc(25*sizeof(char));(*p).author = malloc(25*sizeof(char));

Page 10: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

10TDBA66 Lecture Ch9 vt-03

the operator -> • Instead of the dot operator acting on a certain struct

we can use the operator -> directly on a pointer to the struct

Ex. (*p).title p->title

• The example ones again

typedef struct { char *title; int publishedYear; char *author; } Book;

int main(void){ Book *p; p->title = malloc(25*sizeof(char));p->author = malloc(25*sizeof(char));

Page 11: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

11TDBA66 Lecture Ch9 vt-03

example Book pointer#include <stdio.h>

typedef struct { char *title; int publishedYear; char *author; } Book;

int main(void){ Book *b; (*b).title = "Bilbo - en hobbits äventyr"; b->author = "J.J.R. Tolkien"; (*b).publishedYear= 1935; printf("Title : %s \n",b->title); printf("Author: %s \n",b->author); printf("Published: %d\n",b->publishedYear);

return 0;}/* main */

Page 12: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

12TDBA66 Lecture Ch9 vt-03

example BookList#include <stdio.h>#include <stdlib.h>

typedef struct { char *title; int publishedYear; char *author; } Book;

void writeLibrary(Book *, int);int main(void){ Book *list; int i; int n = 3;

list = calloc(25,sizeof(Book));

for (i=0; i <= n-1;i++) { list[i].title = calloc(25,sizeof(char)); list[i].author = calloc(25,sizeof(char));

}

Page 13: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

13TDBA66 Lecture Ch9 vt-03

... BookList

for (i=0; i <= n-1;i++) { printf("Title[%d] : ",i); gets(list[i].title);

printf("Author : "); gets(list[i].author);

printf("Publishing year: "); scanf("%d",&list[i].publishedYear); getchar(); /* to

skip \n */ }

writeLibrary(list,n);

}

Page 14: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

14TDBA66 Lecture Ch9 vt-03

... skrivBibliotek

void writeLibrary(Book *bib, int no_of){ int i; for (i=0; i <= no_of-1;i++) { printf("Book #%d\n",i); printf("Title : %s\n",bib[i].title); printf("Author : %s\n",bib[i].author); printf("Publishing year : %d\n\n",bib[i].publishedYear);

}}/* writeLibrary */

Page 15: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

15TDBA66 Lecture Ch9 vt-03

peppar:~/c/Ckod> ./a.outTitle[0] : Cprogram Design for EnginnersAuthor : Hanly, KoffmanPublishing year: 2002Title[1] : A Book on CAuthor : Kelley, PohlPublishing year: 1998Title[2] : Problem Solving & Program Design in CAuthor : Hanly, KoffmanPublishing year: 2003Book #0Title : Cprogram Design for EnginnersAuthor : Hanly, KoffmanPublishing year : 2002

Book #1Title : A Book on CAuthor : Kelley, PohlPublishing year : 1998

Book #2Title : Problem Solving & Program Design in CAuthor : Hanly, KoffmanPublishing year : 2003

Run

Page 16: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

16TDBA66 Lecture Ch9 vt-03

/* * Gets and returns a Book structure */Bookget_book(void){

Book b; b.title = (char *) calloc(25,sizeof(char));b.author = (char *) calloc(25,sizeof(char));printf("Title:”);gets(b.title);printf("Author: ”);gets(b.author);printf("Publishing year: ");scanf("%d",&b.publishedYear); getchar(); /* to skip \n */ return (b);}

Function can return a struct

Page 17: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

17TDBA66 Lecture Ch9 vt-03

BookList (version 2)#include <stdio.h>#include <stdlib.h>

typedef struct { char *title; int publishedYear; char *author; } Book;

void writeLibrary(Book *, int);Book get_book(void);int main(void){ Book *list; int i; int n = 3; list = (Book *) calloc(25,sizeof(Book)); for (i=0; i <= n-1;i++) list[i]=get_book();

writeLibrary(list,n);}

Page 18: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

18TDBA66 Lecture Ch9 vt-03

peppar:~/c/Ckod> ./a.outTitle:Differential EquationsAuthor: DavisPublishing year: 1995Title:Numerical Linear Algebra and OptimizationAuthor: Gill, Murray, WrightPublishing year: 1990Title:Matrix ComputationsAuthor: Golub, van LoanPublishing year: 1988Book #0Title : Differential EquationsAuthor : DavisPublishing year : 1995

Book #1Title : Numerical Linear Algebra and OptimizatioGill, Murray, WrightAuthor : Gill, Murray, WrightPublishing year : 1990

Book #2Title : Matrix ComputationsAuthor : Golub, van LoanPublishing year : 1988

Run version 2

Page 19: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

19TDBA66 Lecture Ch9 vt-03

#include <stdio.h>struct dept { char avd[50]; float man_lon; long anst_nr; };struct retired { float pension; int slut_ar; };typedef struct{ char namn[80]; char persnr[10]; char telnr[20]; char jobbkod; union{ struct dept arbetare; struct retired PROman; } variant;} pers_post;

Page 20: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

20TDBA66 Lecture Ch9 vt-03

void main(void) pers_post p1, p2, p3; printf("\nMata in namn:"); scanf("%s", p1.namn); fflush(stdin); printf("\nInmatat namn= %s", p1.namn); printf("\nGe jobbkod (A eller P):"); scanf("%c", &p1.jobbkod); fflush(stdin); printf("\nJobbkod= %c\n", p1.jobbkod); switch (p1.jobbkod){ case 'a': case 'A’: printf("\nGe avdelningsnamn:"); scanf ("%s",p1.variant.arbetare.avd); fflush(stdin); /* OSV */ break; case 'p': case 'P': printf("\nGe årspension: "); scanf("%f", &p1.variant.PROman.pension); printf("Pension= %10.2f\n”, &p1.variant.PROman.pension); fflush(stdin); /* OSV */ break; } p2=p1;}

Page 21: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

21TDBA66 Lecture Ch9 vt-03

Text files

Text file contains ASCII-characters

New line and end-of-file are special characters in a text file

Ex. 1

This is a text<newline>It has two lines<newline><end-of-file>

Examples of predifined text files

stdin, stdout, stderr (these are file pointers)

stderr always associated with the screen

stdin, stdout might be re-directed to other text files

Page 22: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

22TDBA66 Lecture Ch9 vt-03

EOF

EOF is defined in <stdio.h> and is returned from scanf() or fscanf() if end-of-file of the read file is detected

Possible to check if EOF is read by

e.g.

for (status=scanf(”%d”, &num); status != EOF; status=scanf(”%d”, &num))

process(num);

e.g.

while (fscanf(infpt,”%d”, &num) != EOF)

process(num);

Page 23: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

23TDBA66 Lecture Ch9 vt-03

Using text files• Declare file pointers

• Open a file for reading or writing

• -check if opening was ok

• Use it/them

• Close them before ending program

Ex. 1FILE *inf, *outf; if ((inf=fopen(”filname1.txt”,”r”)) == NULL){ fprintf(stderr,”Error when opening filname1.txt”);

exit(-1); } if ((outf=fopen(”filname2.txt”,”w”))== NULL){

fprintf(stderr,”Error when opening filname2.txt”); exit(-2);

}

Page 24: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

24TDBA66 Lecture Ch9 vt-03

/* Makes a backup file. Repeatedly prompts for the name of a file to * back up until a name is provided that corresponds to an available * file. Then it prompts for the name of the backup file and creates * the file copy. */#include <stdio.h>#define STRSIZ 80intmain(void){ char in_name[STRSIZ], /* strings giving names */ out_name[STRSIZ]; /* of input and backup files */ FILE *inp, /* file pointers for input and */ *outp; /* backup files */ char ch; /* one character of input file */ int status; /* status of input operation */ /* Get the name of the file to back up and open the file for input*/ printf("Enter name of file you want to back up> "); for (scanf("%s", in_name); (inp = fopen(in_name, "r")) == NULL; scanf("%s", in_name)) { printf("Cannot open %s for input\n", in_name); printf("Re-enter file name> "); }

Page 25: 1 TDBA66 Lecture Ch9 vt-03 Type declaration Possible to create user defined data types Used to give special names for a certain data type typedef data

25TDBA66 Lecture Ch9 vt-03

/*Get name to use for backup file and open file for output */ printf("Enter name for backup copy> "); for (scanf("%s", out_name); (outp = fopen(out_name, "w")) == NULL; scanf("%s", out_name)) { printf("Cannot open %s for output\n", out_name); printf("Re-enter file name> "); } /* Make backup copy one character at a time */ for (status = fscanf(inp, "%c", &ch); status != EOF; status = fscanf(inp, "%c", &ch)) fprintf(outp, "%c", ch);

/* Close files and notify user of backup completion */ fclose(inp); fclose(outp); printf("Copied %s to %s.\n", in_name, out_name);

return(0);}