I am writing a program in C and I am trying to create these structs.
I have three of them:
the first consisting of 2 ints and 2 chars,
the second consisting of an int and an undefined array of pointers to the first one,
and a third which contains 4 longs and 2 ints along with an undefined array of pointers to the second.
I am having trouble I believe with memory allocation for these structs when instantiated. Does anyone know what I am doing wrong (code below). Cache_Simulator is the main class and uses the others. Any help appreciated.
Directory_block.c
#include <stdio.h>
#include <stdlib.h>
#include "Directory_Block.h"
/* Created September, 15th, 2010;
*
* Author: TJ, Cory
*/
char containsData(directory_block* checkMe){
return checkMe->valid;
}
void setValidOn(directory_block* checkMe){
checkMe->valid = 1;
}
void setValidOff(directory_block* checkMe){
checkMe->valid = 0;
}
char isOlder(directory_block* checkMe, int currentOldest){
if(currentOldest < checkMe->LRU){
return 1;
}
else{
return 0;
}
}
void setTag(directory_block* setMe, int tag){
setMe->tag = tag;
}
char matchesTag(directory_block* checkMe, int theirTag){
if(checkMe->tag == theirTag){
return 1;
}
else{
return 0;
}
}
void incrementLRU(directory_block* incrementMe){
incrementMe->LRU++;
}
void setLRU(directory_block* editMe, int LRUVal){
editMe->LRU = LRUVal;
}
cache_set* createSet(int setNumber,int numberOfBlocks,int printDetails){
cache_set* newSet = malloc(sizeof(cache_set) + sizeof(directory_block)*numberOfBlocks);
newSet->setNumber = setNumber;
printf("Making Set %d\n",newSet->setNumber);
int i = 0;
for(; i < numberOfBlocks;i++)
{
printf("\tMaking Block #%d ",i);
if((i%4)==0&&i!=0)
{
printf("\n");
}
directory_block* block = malloc(sizeof(directory_block));
newSet->blocks[i] = block;
setValidOff(newSet->blocks[i]);
setTag(newSet->blocks[i],setNumber);
setLRU(newSet->blocks[i],-1);
if(printDetails == 1)
{
printf("\tAddress %d\n",(int)newSet->blocks[i]);
printf("\t\tValid=%d\n\t\tLRU=%d\n\t\tTag=%d\n",newSet->blocks[i]->valid
,newSet->blocks[i]->LRU,newSet->blocks[i]->tag);
}
}
printf("\n");
return newSet;
}
Directory_block.h
#ifndef DIRECTORY_BLOCK_H_
#define DIRECTORY_BLOCK_H_
#include "Directory_Block.h"
struct directory_block;
struct set;
struct cache;
typedef struct{
int tag;
int LRU;
char valid;
char offset;
}directory_block;
typedef struct{
int setNumber;
directory_block* blocks[];
}cache_set;
typedef struct{
int numberOfSets;
int linesPerSet;
long hits;
long misses;
long unknownAccesses;
long flushes;
cache_set* sets[];
}cache;
/*
* params: checkMe - the line of the cache that we are checking
* return: true = valid == 1; false valid == 0
*/
char containsData(directory_block* checkMe);
/*
* functions: to set the valid bit to 1
*/
void setValidOn(directory_block* checkMe);
/*
* functions: to set the valid bit to 0
*/
void setValidOff(directory_block* checkMe);
/*
* params: currentOldest - the current oldest in directory_block*
* return: the oldest current directory_block*
*/
char isOlder(directory_block* checkMe, int currentOldest);
/*
* params: theirTag - the tag that is in the directory_block*
* return: 0 if false; 1 is true
*/
char matchesTag(directory_block* checkMe, int theirTag);
/*
* function: increments the value of the LRU in the block
*/
void incrementLRU(directory_block* incrementMe);
void setTag(directory_block* setMe, int tag);
/*
* param: LRUVal - value to set to LRU to (negative means hasn't been used)
*/
void setLRU(directory_block* editMe,int LRUVal);
/*
* param: numberOfBlocks number of blocks per set
* creates a set and instantiates all directory blocks;
* param: setNumber number of this set in the cache
*/
cache_set* createSet(int setNumber,int numberOfBlocks,int details);
#endif /* DIRECTORY_BLOCK_H_ */
Cache.c
#include "Directory_Block.h"
#include <stdio.h>
#include <stdlib.h>
directory_block* findLRU(cache* checkMe,int index){
int age;
age = 0;
int i = 0;
int oldest = 0;
for(; i < checkMe->numberOfSets;i++)
{
if(isOlder(checkMe->sets[i]->blocks[index],age) == 1)
{
oldest = i;
age = checkMe->sets[i]->blocks[index]->LRU;
}
}
return checkMe->sets[i]->blocks[i];
}
int readInAddress(cache checkMe,char fileName[]){
return 0;
}
cache *makeCache(int numberOfLines,int numberOfSets,int details){
cache* returnMe = (cache*)malloc(sizeof(cache) + sizeof(int)*numberOfSets);
returnMe->numberOfSets = numberOfSets;
returnMe->linesPerSet = numberOfLines;
printf("Making Cache\n");
int i=1;
for(; i < returnMe->numberOfSets;i++){
returnMe->sets[i] = createSet(i,returnMe->linesPerSet,details);
}
return returnMe;
}
void writeToCache(cache *addToMe,int address,int tag,int offset)
{
directory_block* LRUblock = findLRU(addToMe,address);
LRUblock->LRU = 0;
LRUblock->tag = tag;
LRUblock->valid = 1;
LRUblock->offset = offset;
}
char processAddress(cache checkMe,int address){
return 0;
}
void reportCacheStatus(cache *reportMe){
int i = 0;
int j = 0;
for(;i < reportMe->numberOfSets;i++)
{
printf("Set #%d\n",i);
for(j=0;j < reportMe->linesPerSet;j++)
{
printf("\tBlock #%d - Tag=%d Valid=%d LRU=%d Offset=%d\n",j,reportMe->sets[i]->blocks[j]->tag
,reportMe->sets[i]->blocks[j]->valid,reportMe->sets[i]->blocks[j]->LRU
,reportMe->sets[i]->blocks[j]->offset);
}
}
}
Cache.h
#include "Set.h"
#ifndef CACHE_H_
#define CACHE_H_
/*
* params: checkMe - cache which that we will look for LRU at
* index - line index which we will check for LRU in all sets
* return: setIndex - of the LRU block
* function - iterates through sets and compares LRU value of directory_block at given
* index for each set.
*
*/
int findLRU(cache checkMe,int index);
/*
* params: char [] - Name of File to read
* return address struct contains access type and parsed address
*/
int readInAddress(cache checkMe,char[]);
/*
*params: int cacheSize total bytes in cache, int linesPerSet number of blocks per set
*params: int lineSize number of bytes per line
* return int [] pointer with # of fields
* (DEFINE FIELDS)
*/
cache* makeCache(int numberOfLines,int numberOfSets,int details);
/*
* params: int address - perform cpu call for that address and see if there is a
* hit or miss or unknown access type - Update stats
*/
char processAddress(cache checkMe,int address);
void writeToCache(cache *addToMe,int address);
/*
*Prints out display of information
*For passes cache
*Ex.
* INSERT EXAMPLE LINE
*/
void reportCacheStatus(cache* reportMe,int numberOfSets,int blocksPerSet);
#endif /* CACHE_H_ */
Cache_simulator.c
#include <stdio.h>
#include <stdlib.h>
#include "fileParser.h"
#include "Directory_Block.h"
#include "Cache.h"
void setupCache(int details);
void performTrace(void);
void report(void);
int main(void)
{
printf("The Cache Simulator:\n\tJonathan Katon\n\tCory Brett\n\tThomas Pavlu\n");
setupCache(1);
//performTrace();
report();
return 0;
}
void setupCache(int details)
{
int numberOfLines = 1024/1;
int numberOfSets = numberOfLines/4;
numberOfLines = numberOfLines/numberOfSets;
printf("Number of Sets %d \nNumber of Lines Per Set %d\n",numberOfSets,numberOfLines);
printf("Cache Size %d,Cache_Set Size %d,Directory_block Size %d",sizeof(cache),sizeof(cache_set),sizeof(directory_block));
cache *instructionCache = makeCache(numberOfLines,numberOfSets,details);
//writeToCache(instructionCache,0);
reportCacheStatus(instructionCache,numberOfSets,numberOfLines);
}
void performTrace(void)
{
FILE* trace;
trace = fopen("trace.txt","r");
readNextMemoryAccess(trace);
}
void report(void)
{ // T.B.D
}
From an 'answer' by the OP about the question:
This was my attempt to try and fix a problem I was having with the memory at least i think I was. When I do a sizeof(cache_set) only it only returns a size large enough for everything but the array of pointers. This makes sense because the array isn't finite my question is how do I get around this issue? Any suggestions. Oh, and by the way, thanks for taking at look at this.
in Directory_block.c
cache_set* newSet = malloc(sizeof(cache_set) + sizeof(directory_block)*numberOfBlocks);
newSet is a pointer with space for:
1 cache_set: ok
numberOfBlocks directory_blocks: huh?
This is wrong: cache_sets do not have directory_blocks in them; they have pointers to directory_blocks
typedef struct{
int setNumber;
directory_block* blocks[];
}cache_set;
I'd pay great attention to your type structure. Do you really need an array of pointers to directory_blocks inside cache_sets? If you do, the typedef is ok; if you don't, it's (probably) the code that's ok ... but, anyway, ... the structure and the malloc don't match.
Edit use the flexible array member
Suppose we have a struct with a flexible array member
struct Example {
int value;
double fam[]; /* fam is the flexible array, of doubles */
};
and now we want to use a variable of type struct Example with space for 100 doubles:
struct Example *example;
example = malloc(sizeof *example + 100 * sizeof *example->fam);
if (example) {
/* use example, eg: */
example->fam[42] = 3.14159265;
/* and remember to free the allocated object when done */
free(example);
}
Related
I recently got an assignment to sort members in a struct by last name and if they are the same to sort by first name. What i have so far only reads their name and age from the file but I am not properly grapsing how I would be able to sort it. So far I gathered the data from the file but im at a loss from there. I followed a code I saw but i didnt get a proper grasping of the process so i reverted back to step one.
struct Members{
int id;
char fname[50];
char lname[50];
int age;
}bio;
int main(){
int i=0;
FILE *fptr;
file = fopen("Members Bio.txt", "r");
while ( fscanf(file, "%d%s%s%d", &bio[i].id,bio[i].fname,bio[i].lname,&bio[i].age) != EOF)
{
printf("%d %s %s %d %d\n", bio[i].id,bio[i].fname, bio[i].lname, bio[i].age);
i++;
}
fclose(fptr);
}
Can anyone help me out on this one?
Code goes something like this for your case.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Members{
int id;
char fname[50];
char lname[50];
int age;
};
typedef int (*compare_func)(void*, void*);
int struct_cmp(void* s1, void* s2)
{
int l_result = strcmp(((struct Members*) s1)->lname, \
((struct Members*) s2)->lname);
if (l_result < 0)
return 1;
else if (l_result > 0)
return 0;
else
return (strcmp(((struct Members*) s1)->fname, \
((struct Members*) s2)->fname) < 0 ? 1 : 0);
}
void sort(void* arr,long ele_size,long start,long end,compare_func compare)
{
// Generic Recursive Quick Sort Algorithm
if (start < end)
{
/* Partitioning index */
void* x = arr+end*ele_size;
long i = (start - 1);
void* tmp=malloc(ele_size);
for (long j = start; j <= end - 1; j++)
{
if ((*compare)(arr+j*ele_size,x))
{
i++;
// Swap is done by copying memory areas
memcpy(tmp,arr+i*ele_size,ele_size);
memcpy(arr+i*ele_size,arr+j*ele_size,ele_size);
memcpy(arr+j*ele_size,tmp,ele_size);
}
}
memcpy(tmp,arr+(i+1)*ele_size,ele_size);
memcpy(arr+(i+1)*ele_size,arr+end*ele_size,ele_size);
memcpy(arr+end*ele_size,tmp,ele_size);
i= (i + 1);
sort(arr,ele_size,start, i - 1,compare);
sort(arr,ele_size,i + 1, end,compare);
}
}
int main()
{
FILE* fp;
int bio_max = 3;
struct Members bio[bio_max]; // Define bio to be large enough.
/* Open FILE and setup bio matrix */
/* For testing */
bio[0].id = 0;
strcpy(bio[0].fname, "");
strcpy(bio[0].lname, "Apple");
bio[0].age = 0;
bio[1].id = 1;
strcpy(bio[1].fname, "");
strcpy(bio[1].lname, "Cat");
bio[1].age = 1;
bio[2].id = 2;
strcpy(bio[2].fname, "");
strcpy(bio[2].lname, "Bat");
bio[2].age = 2;
/* Sort the structure */
sort(bio, sizeof(struct Members), 0, bio_max - 1, struct_cmp);
/* Print the sorted structure */
for (int i = 0; i < bio_max; i++) {
printf("%d %s %s %d\n", bio[i].id, bio[i].fname, \
bio[i].lname, bio[i].age);
}
}
Output
0 Apple 0
2 Bat 2
1 Cat 1
If the strings are not sorting in the way you want, you can redefine the struct_cmp function. Code is self explanatory, the base logic in the code is pass an array and swap elements using memcpy functions. You cant use simple assignment operator if you want to be generic, so that is why the element size is explicitly passed.
Edit
The code was not handling the condition, if lname are same. I missed it thanks for #4386427 for pointing this out.
I think you should define bio to be an array. And google sort algorithms please. Also recommend you google how to use libc function qsort.
Since the array address may change when memory is reallocated,
the main part of the program (in the body of the function main ()) should refer to the elements by
indexes, not pointers. Why?
Can you show an example of accessing items with pointers?
(Sorry for my English).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Nameval Nameval;
struct Nameval {
char *name;
int value;
};
struct NVtab {
int nval; /* current number of values */
int max; /* allocated number of values */
Nameval *nameval; /* array of name-value pairs */
};
enum {NVINIT = 1, NVGROW = 2};
/* addname: add new name and value to nvtab */
int addname(struct NVtab *nvtab, Nameval newname) {
Nameval *nvp;
if (nvtab->nameval == NULL) { /* first time */
nvtab->nameval = (Nameval *) malloc(NVINIT * sizeof(Nameval));
if (nvtab->nameval == NULL)
return -1;
nvtab->max = NVINIT;
nvtab->nval = 0;
} else if (nvtab->nval >= nvtab->max) { /* grow */
nvp = (Nameval *) realloc(nvtab->nameval,
(NVGROW*nvtab->max)*sizeof(Nameval));
if (nvp == NULL)
return -1;
nvtab->max *= NVGROW;
nvtab->nameval = nvp;
}
nvtab->nameval[nvtab->nval] = newname;
return nvtab->nval++;
}
int main(void) {
struct NVtab nvtab = {0, 0, NULL};
int curnum;
curnum = addname(&nvtab, (Nameval) {.name="Andy", .value=12});
printf("%d\n", curnum);
curnum = addname(&nvtab, (Nameval) {.name="Billy", .value=18});
printf("%d\n", curnum);
curnum = addname(&nvtab, (Nameval) {.name="Jack", .value=71});
printf("%d\n", curnum);
for (int i = 0; i < nvtab.nval; i++) {
printf("%s %d\n", nvtab.nameval[i].name,
nvtab.nameval[i].value);
}
}
For example, why can`t we show array like this:
for (int i = 0; i < nvtab.nval; i++)
printf("%s %d\n", nvtab.*(nameval+i).name, nvtab.*(nameval+i).value);
You are not supposed to assign a pointer calculated for a specific index to a variable with storage duration which could extend over an insert operation.
That pointer could become invalid, so the lesson behind that example is to always re-evaluate iterators on dynamic data structures.
E.g. what not to do:
auto *foo = &nvtab.nameval[i];
addname(&nvtab, (Nameval) {.name="Billy", .value=18});
printf("%s %d\n", foo->name, foo->value);
In the last line it can work or crash. Depending on whether realloc moved the allocation or resized in-place. Except that you can never know for sure until you execute it, as it isn't even fully deterministic.
This is not valid syntax:
nvtab. *(nameval+i).name
The member access operator . expects to be followed by the name of the member. What you want is:
(*(nvtab.nameval+i)).name
I'm a C beginner, I want to call ungetc() twice in a row although I know in regular C it is not permitted. Someone told me I can modify Fflush() to do this job, however I don't know how to do it.
Here is my code, my Fflush only allow one ungetc(), I want it to allow twice.
#define altUngetc(c, fp) ((fp)->next > (fp)->buffer && (c) != EOF ? \
*--(fp)->next = (c) : EOF)
int altGetc(ALT_FILE *fp) {
if (fp->next == fp->buffer + fp->bufSize)
altFflush(fp);
return fp->flags & FILE_ATEOF ? EOF : *fp->next++;
}
int altFflush(ALT_FILE *fp) {
int res;
if (fp->fd < 0 || fp->flags & FILE_ATEOF)
return EOF;
if (fp->flags & FILE_READ) {
res = read(fp->fd, fp->buffer, BUF_SIZE);
if (res == 0)
fp->flags |= FILE_ATEOF;
fp->bufSize = res;
fp->next = fp->buffer;
}
else {
res = write(fp->fd, fp->buffer, fp->next - fp->buffer);
fp->next = fp->buffer;
}
return res < 0 ? EOF : 0;
}
As wisely mentioned in the comments, you should probably first learn to work with the rules instead of trying to break them. However, we're here to answer the question, and that means to break the rules! Take into account that neither fflush(), setbuf(), or setvbuf() would work here for different reasons.
First of all, at least four custom functions are required. One to create a "proxy buffer" relating to a file (called just after fopen()), one to destroy it (called just before fclose(), one to do the actual ungetting (replacement for ungetc(), and one to to retrieve a char from the file (replacement for fgetc(). Unfortunately, this means that performing fscanf(), fflush(), etc... on the stream will yield you bad and ugly results. You would have to rewrite all of stdio!
First of all, let's call all of our new stuff xtdio ("extended stdio"), so, first of all comes xtdio.h...
#ifndef __XTDIO_H__
#define __XTDIO_H__
#include <stdio.h>
typedef struct
{
FILE *file;
char *buffer;
size_t buffer_size;
size_t buffer_usage;
size_t buffer_tail_offset;
} XFILE;
/* I know this is not the best of API design, but I need to be
* compatible with stdio's API.
*/
XFILE *xwrap(FILE *file, size_t max_ungets);
void xunwrap(XFILE *xfile);
int xgetc(XFILE *xfile);
int xungetc(int ch, XFILE *xfile);
#endif
Then, in the interesting side of the fence, comes xtdio.c...
#include <stdlib.h>
#include <stdio.h>
#include "xtdio.h"
/* Create a XFILE wrapper, along with its respective buffer
* of 'max_ungets' size, around 'file'.
*/
XFILE *xwrap(FILE *file, size_t max_ungets)
{
XFILE *xfile = malloc(sizeof(XFILE));
if(xfile == NULL)
return NULL;
xfile->file = file;
xfile->buffer = malloc(max_ungets);
if(xfile->buffer == NULL) {
free(xfile);
return NULL;
}
xfile->buffer_size = max_ungets;
xfile->buffer_usage = 0;
xfile->buffer_tail_offset = 0;
return xfile;
}
/* Undo what 'xwrap()' did.
*/
void xunwrap(XFILE *xfile)
{
free(xfile->buffer);
free(xfile);
}
/* Check if there's something in the XFILE's
* buffer, and return it. Otherwise, fallback
* onto 'fgetc()'.
*/
int xgetc(XFILE *xfile)
{
if(xfile->buffer_usage == 0)
return fgetc(xfile->file);
if(xfile->buffer_tail_offset == 0)
xfile->buffer_tail_offset = xfile->buffer_size - 1;
else
xfile->buffer_tail_offset--;
xfile->buffer_usage--;
return xfile->buffer[xfile->buffer_tail_offset];
}
/* Here's the interesting part! If there's room in the
* buffer, it puts 'ch' in its front. Otherwise, returns
* an error.
*/
int xungetc(int ch, XFILE *xfile)
{
if(xfile->buffer_usage == xfile->buffer_size)
return EOF; //TODO: Set errno or something
xfile->buffer[xfile->buffer_tail_offset++] = (char)ch;
xfile->buffer_tail_offset %= xfile->buffer_size;
xfile->buffer_usage++;
return ch;
}
The smallish xtdio library will allow you to perform as many ungets as you pass to xwrap()'s parameter. Each XFILE has a buffer with the ungotten characters. When you xgetc(), it first checks if there's something on the buffer and retrieves it. Otherwise, it fallbacks to fgetc(). Example usage case...
#include <stdio.h>
#include <string.h>
#include "xtdio.h"
int main()
{
const char *my_string = "I just ungot this same long string in standard and compliant C! No more one-char limits on ungetc()!\n";
const size_t my_string_len = strlen(my_string);
XFILE *xtdin = xwrap(stdin, my_string_len);
if(xtdin == NULL) {
perror("xwrap");
return 1;
}
for(size_t i = my_string_len; i != 0; i--)
xungetc(my_string[i - 1], xtdin);
int ch;
while((ch = xgetc(xtdin)) != EOF)
putchar(ch);
xunwrap(xtdin);
return 0;
}
xtdio can be further improved, by adding things such as xrewrap() to extend/shrink the buffer's size.
There's an even better solution, and it is to refactor your code, and follow the conventions, so that you don't have to ungetc() twice. xtdio is just a proof of concept, but is not good code, and shall never be used in practice. This way, you won't have to deal with rewriting stdio.
If you know how to implement a int stack, you can create your own ungetc() function. Simply replace calls of ungetc() with a myungetc() (etc) that if that stack has values, pop them instead of reading from getc(). Whenever you want to un-get, simply push values on to the stack in the reverse order you read them.
An example from a recent project of mine:
/* stack.h */
#ifndef _STACK_H_
#define _STACK_H_
typedef struct {
int * vals;
int currsize;
int maxsize;
} stack;
int stack_init(stack * this, int size);
void stack_destroy(stack * this);
void push(stack * this, int val);
int pop(stack * this);
int isempty(stack * this);
int isfull(stack * this);
int size(stack * this);
int maxsize(stack * this);
#endif
/* stack.c */
#include <stdlib.h>
#include "stack.h"
#define THIS (this)
#define VALS (this->vals)
#define CURRSIZE (this->currsize)
#define MAXSIZE (this->maxsize)
int stack_init(stack * this, int size) {
VALS = malloc(sizeof(int)*size);
CURRSIZE = 0;
MAXSIZE = size;
if (!VALS) {
return 1; /* alloc fail */
}
return 0; /* successful init */
}
void stack_destroy(stack * this) {
free(VALS);
}
void push(stack * this, int val) {
if (isfull(THIS)) {
return;
}
VALS[CURRSIZE++] = val;
}
int pop(stack * this) {
if (isempty(THIS)) {
return 0;
}
return VALS[--CURRSIZE];
}
int isempty(stack * this) {
return (CURRSIZE == 0);
}
int isfull(stack * this) {
return (CURRSIZE == MAXSIZE);
}
int size(stack * this) {
return CURRSIZE;
}
int maxsize(stack * this) {
return MAXSIZE;
}
#undef THIS
#undef VALS
#undef CURRSIZE
#undef MAXSIZE
/* main.c */
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
int stgetc(FILE * stream, stack * pushed) { /* The getc() equivalent */
if (isempty(pushed)) {
return getc(stream);
} else {
return pop(pushed);
}
}
int stpush(int val, stack * pushed) { /* The ungetc() equivalent */
if (isfull(pushed)) {
return 1;
} else {
push(pushed,val);
return 0;
}
}
int main(int argc, char ** argv) {
/* startup code, etc. */
stack pushbuf; /* where the pushback will be stored */
stack_init(&pushbuf, 32) /* 32 = maximum number of ungetc calls/characters we can push */
FILE * in = fopen("/some/file","r");
/* file read */
int readchar;
while ((readchar = stgetc(in,pushbuf)) != EOF) {
/* do stuff */
stpush(readchar,pushbuf); /* oops, read too much! */
}
fclose(&in); /* close file */
stack_destroy(&pushbuf); /* clean up our buffer */
/* ... */
}
(I apologize for the wall of text but a shorter example isn't possible)
Considering you seem to be working with a file, it should be possible to fseek() backwards, although this will work for both files and stdin.
So, I have the functions. How can I insert numbers in the Hashtable? A for that goes until the size of the table? I don't know what goes inside the for, if it is exists.
#include <stdio.h>
//Structure
typedef struct Element {
int key;
int value;
} Element;
typedef struct HashTable {
Element *table[11];
} HashTable;
//Create an empty Hash
HashTable* createHashTable() {
HashTable *Raking = malloc(sizeof(HashTable));
int i;
for (i = 0; i < 11; i++) {
Raking->table[i] = NULL;
}
return Raking;
}
//Insert element
void insertElement(HashTable *Raking, int key, int value) {
int h = hashFunction(key);
while(Raking->table[h] != NULL) {
if(Raking->table[h]->key == key) {
Raking->table[h]->value = value;
break;
}
h = (h + 1) % 11;
}
if(Raking->table[h] == NULL) {
Element *newElement = (Element*) malloc(sizeof(Element));
newElement->key = key;
newElement->value = value;
Raking->table[h] = newElement;
}
}
int main() {
HashTable * Ranking = createHashTable();
/** ??? **/
}
Could someone explain to me how to write my main function with these structures? In this case I'm fixing the number of elements in this table, right? (table [11]) What could I do for the user to determine the size of the hash table? is it possible? Or should I set the size?
I've added comments and changes to your code that I feel will be of use to you. I've also adapted it so that size is not hardcoded. Finally I free all the malloc-ed statements.
This compiles without errors and I've tested it for memory leaks and other errors using valgrind and found no complaints.
Let me know if something is not clear and the comments fail to explain it. I've tried to stick to your code as much as possible but I've not had a chance to test the functionality properly.
#include <stdio.h>
#include <stdlib.h>
//Structure
typedef struct Element {
int key;
int value;
} Element; /* you had a syntax error here */
typedef struct HashTable {
int size; /* we will need the size for the traversal */
Element *table; /* leave it as a pointer */
} HashTable; /* a syntax error here too */
HashTable* createHashTable(int size) {
HashTable *Ranking = malloc(sizeof(HashTable));
/* set the pointer to point to a dynamic array of size 'size' */
/* this way you don't have to hardcode the size */
Ranking->table = malloc(sizeof(Element) * size);
Ranking->size = size;
/* initialisation is a bit different because we don't have pointers here */
/* only table is a pointer, not its elements */
int i;
for (i = 0; i < size; i++) {
Ranking->table[i].key = 0;
Ranking->table[i].value = 0;
}
return Ranking;
}
/* I implemented a fake hashFunction just to test the code */
/* all it does is make sure the key does not exceed the size of the table */
int hashFunction(int key, int size)
{
return (key % size);
}
//Insert element
void insertElement(HashTable *Ranking, int key, int value) {
int h = hashFunction(key, Ranking->size);
int i = 0;
/* if hash is full and key doesn't exist your previous loop would have gone on forever, I've added a check */
/* also notice that I check if table[h] has empty key, not if it's null as this is not a pointer */
while(Ranking->table[h].key != 0 && (i < Ranking->size)) {
if(Ranking->table[h].key == key) {
Ranking->table[h].value = value;
return; /* break is intended to quit the loop, but actually we want to exit the function altogether */
}
h = (h + 1) % Ranking->size; /* changed 11 to the size specified */
i++; /* advance the loop index */
}
/* okay found a free slot, store it there */
if(Ranking->table[h].key == 0) {
/* we now do direct assignment, no need for pointers */
Ranking->table[h].key = key;
Ranking->table[h].value = value;
}
}
int main() {
int size = 0;
scanf(" %d", &size);
HashTable *Ranking = createHashTable(size);
insertElement(Ranking, 113, 10); /* this is just a test, 113 will be hashed to be less than size */
/* we free everything we have malloc'ed */
free(Ranking->table);
free(Ranking);
return 0;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I seem to be going in circles with this project! I get so many errors of 'dereferencing pointer to incomplete type', and have quite a few others. it seems like when I fix one another one will pop up to take its place!
It's my first time using hash tables, and I admit that I am rather lost but I think I made a very good start at least. Any input as to how to solve my 'dereferencing pointer to incomplete type' problems would be amazing!
htable.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "htable.h"
struct htablerec {
int size;
int num_entries;
hashing_t method;
char **keys;
int *freqs;
int *stats;
};
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
/*moves pointer to point to something appropriate*/
htable htable_new(int capacity) {
int i;
htable ht = emalloc(sizeof *ht);
ht->size = size;
ht->method = method;
ht->num_keys = 0;
ht->keys = emalloc(size * sizeof ht->keys[0]);
ht->freqs = emalloc(size * sizeof ht->freqs[0]);
ht->stats = emalloc(size * sizeof ht->stats[0]);
for(i = 0; i<size; i++){
ht->keys[i] = NULL;
ht->freqs[i] = 0;
ht->stats[i] = 0;
}
return ht;
}
static unsigned int htable_step(htable h, unsigned int i_key){
return 1 + (i_key % (h->size - 1));
}
static unsigned int htable_wtoi(char *word){
unsigned int result = 0;
while(*word != '\0') result = (*word++ +31 * result);
return result;
}
static unsigned int htable_hash(htable h, unsigned int i_key){
return i_key % h->size;
}
void htable_free(htable h) {
int i;
for(i = 0; i<h->size; i++){
if(h->keys[i] != NULL){
free(h->keys[i]);
}
}
if(h->keys != NULL){
free(h->keys);
}
if(h->freqs != NULL){
free(h->freqs);
}
free(h);
}
static unsigned int htable_word_to_int(char *word) {
unsigned int result = 0;
while (*word != '\0') {
result = (*word++ + 31 * result);
}
return result;
}
int htable_insert(htable h, char *str) {
int num_collisions = 0;
int i_key = htable_wtoi(key);
int pos = htable_hash(h, i_key);
int step = 1;
if(h->method == DOUBLE)
step = htable_step(h, i_key);
while(h->keys[pos]!=NULL &&
strcmp(h->keys[pos],key)!=0 &&
num_collisions < h->size ){
pos = htable_hash(h, pos + step);
num_collisions++;
}
if(h->keys[pos] == NULL){
h->keys[pos] = emalloc((strlen(key)+1) * sizeof h->keys[0][0]);
strcpy(h->keys[pos],key);
h->stats[h->num_keys] = num_collisions;
h->num_keys++;
}
if(num_collisions >= h->size) /* We must be full, so return zero.*/
return 0;
return ++(h->freqs[pos]);
}
static int htable_search(htable h, char *key){
int num_collisions = 0;
int i_key = htable_wtoi(key);
int pos = htable_hash(h, i_key);
int step = 1;
if(h->method == DOUBLE)
step = htable_step(h, i_key);
while(h->keys[pos]!=NULL &&
strcmp(h->keys[pos],key)!=0 &&
num_collisions < h->size ){
pos = htable_hash(h, pos + step);
num_keys++;
}
if(num_keys >= h->size)
return 0;
else
return h->freqs[pos];
}
void htable_print(htable h, FILE *stream){
int i;
for(i = 0; i<h->size; i++){
if(h->keys[i] != NULL)
fprintf(stream, "%d\t%s\n",i, h->freqs[i], h->keys[i]);
}
}
void htable_print_entire_table(htable h, FILE *stream) {
int i;
for (i=0; loop < h->capacity; i++) {
if (h->key[i] != NULL) {
fprintf("%d\t%s\n", h->freqs[i], h->key[i]);
}
}
}
/**
* Prints a line of data indicating the state of the hash table when
* it is a given percentage full.
*
* The data is printed out right justified (with the given field widths,
* and decimal places) in this order:
*
* - How full the hash-table is as a percentage (4)
* - How many keys are in the hash-table at that point (11)
* - What percentage of those keys were placed 'at home' (12, 1 dp)
* - The average number of collisions per key placed (12, 2 dp)
* - The maximum number of collisions while placing a key (12)
*
* #param h the hash-table to get data from.
* #param stream the place to send output to.
* #param percent_full the point at which to print the statistics.
* If the hashtable is less full than that, then
* nothing will be printed.
*/
static void print_stats_line(htable h, FILE *stream, int percent_full) {
int current_entries = h->capacity * percent_full / 100;
double average_collisions = 0.0;
int at_home = 0;
int max_collisions = 0;
int i = 0;
if (current_entries > 0 && current_entries <= h->num_keys) {
for (i = 0; i < current_entries; i++) {
if (h->stats[i] == 0) {
at_home++;
}
if (h->stats[i] > max_collisions) {
max_collisions = h->stats[i];
}
average_collisions += h->stats[i];
}
fprintf(stream, "%4d%11d%12.1f%12.2f%12d\n", percent_full,
current_entries, at_home * 100.0 / current_entries,
average_collisions / current_entries, max_collisions);
}
}
void htable_print_stats(htable ht, FILE *stream, int num_stats) {
int i;
fprintf(stream, "Percent Current Percent Average Maximum\n");
fprintf(stream, " Full Entries At Home Collisions Collisions\n");
fprintf(stream, "-----------------------------------------------------\n");
for (i = 1; i <= num_stats; i++) {
print_stats_line(ht, stream, 100 * i / num_stats);
}
fprintf(stream, "-----------------------------------------------------\n\n");
}
htable.h
#ifndef HTABLE_H
#define HTABLE_H
#include <stdio.h>
typedef struct hashtable *htable;
typedef enum hashing_e { LINEAR, DOUBLE } hashing_t;
extern htable htable_new(int size);
extern void htable_destroy(htable ht);
extern int htable_insert(htable h, char *key);
extern int htable_search(htable h, char *key);
extern void htable_print(htable h, FILE *stream);
extern void htable_print_stats(htable ht, FILE *stream, int num_stats);
#endif
main.c (given by tutor for project to fit)
/**
* #file main.c
* #author Iain Hewson
* #date August 2012
*
* This program is written to test the hash table ADT specified in
* Cosc242 assignment two. It creates a hash table which can use
* linear-probing or double-hashing as a collision resolution
* strategy. Various options are provided which make it possible to
* examine a hash table as well as see how it performs while being
* filled.
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "mylib.h"
#include "htable.h"
/* A boolean type which can be TRUE or FALSE */
typedef enum bool_e {FALSE, TRUE} bool_t;
/* function declarations */
static void usage(char *progname);
static void setup(int argc, char **argv, bool_t *double_hashing,
bool_t *entire_table, bool_t *print_stats,
int *snapshots, int *tablesize);
/**
*
* Creates a hash-table and inserts words into it read from stdin.
* Arguments on the command line alter the behaviour of the program
* as follows:
* - -d Use double hashing (linear probing is the default)
* - -e Display entire contents of hash-table on stderr
* - -n NUM Show NUM statistics snapshots (if -p is used)
* - -p Print stats info instead of frequencies & words
* - -s SIZE Use the first prime >= SIZE as htable size
* - -h Display this message
*
* By default each word and it's frequency are printed to stdout.
*
* #param argc the number of command-line arguments.
* #param argv an array of strings containing the command-line arguments.
*
* #return EXIT_SUCCESS if the program is successful.
*/
int main(int argc,char **argv) {
bool_t entire_table = FALSE, double_hashing = FALSE, print_stats = FALSE;
int tablesize = 0, snapshots = 0;
char word[256];
htable ht;
setup(argc, argv, &double_hashing, &entire_table, &print_stats,
&snapshots, &tablesize);
ht = htable_new(tablesize, (double_hashing) ? DOUBLE_H : LINEAR_P);
while (getword(word, sizeof word, stdin) != EOF) {
htable_insert(ht, word);
}
if (entire_table) {
htable_print_entire_table(ht, stderr);
}
if (print_stats) {
htable_print_stats(ht, stdout, snapshots);
} else {
htable_print(ht, stdout); /* print words and frequencies */
}
htable_free(ht);
return EXIT_SUCCESS;
}
/**
* Prints out a usage message to stderr outlining all of the options.
* #param prog_name the name of the program to include in usage message.
*/
static void usage(char *prog_name) {
fprintf(stderr, "Usage: %s [OPTION]... <STDIN>\n\n%s%s", prog_name,
"Perform various operations using a hash-table. By default read\n"
"words from stdin and print them with their frequencies to stdout.\n\n"
" -d Use double hashing (linear probing is the default)\n"
" -e Display entire contents of hash-table on stderr\n",
" -n NUM Show NUM stats snapshots (if -p is used)\n"
" -p Print stats info instead of frequencies & words\n"
" -s SIZE Use the first prime >= SIZE as htable size\n\n"
" -h Display this message\n\n");
}
/**
* Handle options given on the command-line by setting a number of
* variables appropriately. May call usage() if incorrect arguments
* or -h given.
*
* #param argc the number of command-line arguments.
* #param argv an array of strings contain the command-line arguments.
* #param double_hashing set to TRUE if -d given
* #param entire_table set to TRUE if -e given
* #param snapshots set to NUM if -n NUM given and NUM > 0 else set to 10
* #param print_stats set to TRUE if -p given
* #param tablesize set to SIZE if -t SIZE given and SIZE > 0 else set to 113
*/
static void setup(int argc, char **argv, bool_t *double_hashing,
bool_t *entire_table, bool_t *print_stats,
int *snapshots, int *tablesize) {
const char *optstring = "dehpn:s:";
char option;
while ((option = getopt(argc, argv, optstring)) != EOF) {
switch (option) {
case 'd':
*double_hashing = TRUE;
break;
case 'e':
*entire_table = TRUE;
break;
case 'p':
*print_stats = TRUE;
break;
case 'n':
*snapshots = atoi(optarg);
break;
case 's':
*tablesize = atoi(optarg);
break;
case 'h':
default:
usage(argv[0]);
exit(EXIT_SUCCESS);
}
}
/* set default values if nothing sensible entered */
if (*tablesize < 1) *tablesize = 113;
if (*snapshots < 1) *snapshots = 10;
}
mylib.c
#include <stdlib.h>
#include "mylib.h"
/**************************
* *
* emalloc *
* *
**************************
Used to handle new memory allocation to a pointer and handle exceptions
which may arrise if memory allocation fails, which happens all the time
when you try and enter negative values.
PARAMETERS: s = calculated size of required memory.
RETURN VALUE: a pointer of any type.
*/
void *emalloc(size_t s){
void *result = malloc(s);
if(NULL == result){
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
/**************************
* *
* erealloc *
* *
**************************
Handles the reallocation of an updated amount of memory to an existing
with existing data attached.
PARAMETERS: p = the existing pointer we would like additional memory
allocated to.
s = calculated size of required memory.
RETURN VALUE: a pointer of any type.
*/
void *erealloc(void *p, size_t s){
void *result = realloc(p,s);
if(NULL == result){
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
/**************************
* *
* getword *
* *
**************************
Is used to read input from the designated file stream (standard in for the
assignment). Getword removes white space with the first while loop. And only
returns one word. Maintaining continous input is therefore the responsibility
of the calling function.
PARAMETERS: s = the pointer to the character array.
limit = the maximum size a word can be.
stream = where to read from.
RETURN VALUE: the integer value of the character at s[0]. The string s does
not need to be returned, since it is an array and is passed as
a memory address. If no chars were read into the string s, then
s[0] would have the '\0' [NULL] value which equates to 0 if used
in a boolean equation.
*/
int getword(char *s, int limit, FILE *stream){
int c;
while(!isalnum( c = getc(stream)) && c != EOF);
if(c == EOF)
return EOF;
else
*s++ = tolower(c);
while(--limit > 0){
if(isalnum(c = getc(stream)))
*s++ = tolower(c);
else if('\'' == c) continue;
else break;
}
*s = '\0';
return s[0];
}
/**************************
* *
* stoi *
* *
**************************
Not using this function now.
PARAMETERS: s = string representation of a number.
RETURN VALUE: the integer value.
*/
int stoi(char *s){
int i,j,r;
int sign = 1;
i=1;
r=0;
for(j=my_strlen(s)-1; j>=0; j--){
if(j == 0 && s[j] == '-')
sign = -1;
else {
if(s[j]>='0' && s[j]<='9'){
r+=((s[j]-'0')*i);
i*=10;
} else {
fprintf(stderr, "Invalid input for String to int\n");
exit(EXIT_FAILURE);
}
}
}
return r * sign;
}
/**************************
* *
* my_strlen *
* *
**************************
I am using my own string length function, but I wrote it with the stoi
function, so am using it here. Perhaps not as safe as the library
functions?
PARAMETERS: s = a string delimited by the NULL character.
RETURN VALUE: the number of characters in the string.
*/
int my_strlen(char *s){
int i=0;
while(s[i]!='\0')
i++;
return i;
}
/**************************
* *
* factors *
* *
**************************
Another unrequired function used to calculate the possiblity of factorisation.
PARAMETERS: x = An integer to be factored towards.
RETURN VALUE: 0 if x has factors, 1 if x is a prime number.
*/
static int factors(int x){
int f = 2;
while(f*f < x){
if(x % f == 0){
return 0;
} else {
f++;
}
}
return 1;
}
/**************************
* *
* prime_gt *
* *
**************************
Used in conjunction with factors to find factorless integers. We increment
bound until it is truely prime.
Bound - We start with bound, sending it to the factors function. If it is
a prime number, then stop searching. Otherwise loop until we find
an prime integer larger than the input integer.
PARAMETERS: s = the input integer.
RETURN VALUE: Bound, for it is now a prime number.
*/
static int prime_gt(int s){
int bound = s;
while(bound > 0){
if(factors(bound))
break;
else
bound++;
}
return bound;
}
/**************************
* *
* relative_prime *
* *
**************************
Decides on a prime number to use to set the table size to.
PARAMETERS: s = the required size of the table.
RETURN VALUE: the newer beter prime number size for the table.
*/
unsigned int relative_prime(int s){
return prime_gt(s);
}
Sorry for it being so big, it's ok if it's just a complete unfixable jumble.
You don't seem to have defined struct hashtable anywhere. You need to say somewhere what fields that struct should actually contain, at the moment there is only a forward declaration in htable.h.
Such a forward declaration just says that the type exists, but not how it exactly looks like. Therefore it is considered an incomplete type, until the compiler sees a full definition of it.
Cause the definition of struct hashtable does not exist, the following line creates an alias of an incomplete pointer type (htable).
typedef struct hashtable *htable;
It is impossible to deference such pointer (the compiler doesn't know the different fields of your structure).
In your file htable.c, maybe you meant :
/* instead of struct htablered */
struct htable {
int size;
int num_entries;
hashing_t method;
char **keys;
int *freqs;
int *stats;
};