Last active
November 14, 2017 15:02
-
-
Save navin-mohan/e2bddbd7d03e17f9d13f1ee91060bc47 to your computer and use it in GitHub Desktop.
symtab complete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <ctype.h> | |
#include <string.h> | |
#define SYMTAB_SIZE 100 | |
#define SYMBOL_SIZE 30 | |
typedef unsigned int uint; | |
typedef struct{ | |
char sym[SYMBOL_SIZE]; | |
int loc; | |
}Symbol; | |
Symbol symtab[SYMTAB_SIZE]; | |
uint hash_str(char* str){ | |
uint hash = 0; | |
uint n,i; | |
for(i = 0; str[i]; i++){ | |
str[i] = tolower(str[i]); | |
} | |
for(i=0;*(str+i) != '\0';++i){ | |
if(isalpha(*(str+i))) | |
n = *(str+i) - 'a' + 1; | |
else | |
n = 27; | |
hash = ((hash << 3) + n) % SYMTAB_SIZE; | |
} | |
return hash; | |
} | |
void initialize_symtab(){ | |
int i; | |
for(i=0;i<SYMTAB_SIZE;++i){ | |
symtab[i].sym[0] = '\0'; | |
symtab[i].loc = -1; | |
} | |
} | |
void insert_to_symtab(char* sym,int loc){ | |
int hash = hash_str(sym); | |
strcpy(symtab[hash].sym,sym); | |
symtab[hash].loc=loc; | |
} | |
Symbol get_symbol(char* sym){ | |
return symtab[hash_str(sym)]; | |
} | |
int main(void){ | |
int c,loc; | |
char sym[SYMBOL_SIZE]; | |
Symbol s; | |
initialize_symtab(); | |
do{ | |
printf("1. Add a Symbol\n"); | |
printf("2. Look up a Symbol\n"); | |
printf("3. Quit\n"); | |
scanf("%d",&c); | |
switch(c){ | |
case 1:{ | |
printf("Enter Symbol name:"); | |
scanf("%s",sym); | |
printf("Enter Symbol location:"); | |
scanf("%d",&loc); | |
insert_to_symtab(sym,loc); | |
break; | |
} | |
case 2:{ | |
printf("Enter Symbol name:"); | |
scanf("%s",sym); | |
s = get_symbol(sym); | |
if(s.loc == -1) | |
printf("Symbol not found!\n"); | |
else | |
printf("Symbol found!\nName: %s\nLocation: %d\n",s.sym,s.loc); | |
break; | |
} | |
} | |
}while(c != 3); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment