Programming in C

Lecture 8: DATA STRUCTURES

CHRIS STAFF
Dept. of Computer Science and Artificial Intelligence
University of Malta


Lecture Outline

Aims and Objectives
Data Structures
Structures and Functions
Arrays of Structures


Aims and Objectives


Data Structures

Basics


Structures and Functions

A function to make a structure out of variables

struct point makepoint(int x, int y)
{
	struct point temp;

	temp.x = x;
	temp.y = y;
	return temp;
}

Structure Arithmetic

Pointers to Structures

Structure Arithmetic and Pointers


Arrays of Structures

Creating an array of structures

The Program

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "keywords.h"/* assume keywords[] defined here */

#define MAXWORD 100 /* word can be max 100 chars long */

int getword(char *, int);
int binsearch(char *, struct key *, int);

main()
{
	int n;
	char word[MAXWORD];

	while(getword(word, MAXWORD) != EOF)
		if (isalpha(word[0]))
			if ((n=binsearch(word, keytab, NKEYS))>=0)
				keytab[n].count++;
	for (n = 0; n < NKEYS; n++)
		if (keytab[n].count > 0)
			printf("%4d %s\", 
				keytab[n].count, keytab[n].word);
	return 0;
}

/* iterative binsearch modified */

int binsearch(char *word, struct key tab[], int n)
{
	int cond, low, high, mid;

	low = 0;
	high = n - 1;
	while(low <= high) {
		mid = (low+high) / 2;
		if ((cond = strcmp(word, tab[mid].word))<0)
			high = mid - 1;
		else if (cond > 0)
			low = mid + 1;
		else
			return mid;
	}
	return -1;
}

C can calculate the size of your structures