Question: Need help with homework: How to utilize strdup()? What does it do? A) In Insert(), you MUST strdup() the character string, otherwise you will get
Need help with homework:
How to utilize strdup()? What does it do?
A) In Insert(), you MUST "strdup() the character string, otherwise you will get weird results.
B) Create a symbtab.h files which exposes the Insert() and Search() and struct{} definition and include " symbtab.h" it in your *.c file
/**************************************************************************************************************************************************/
#include
#include
#include
#include
struct SymbTab {
char *symbol;
int address;
struct SymbTab *next;
};
struct SymbTab *first, *last;
int size = 0;
struct SymbTab *Insert(char *symbol, int address) {
struct SymbTab *p = first;
while (p != NULL) {
if (strcmp(p->symbol, symbol) == 0) {
printf("Error: symbol already present ");
exit(1);
}
p = p->next;
}
p = malloc(sizeof(struct SymbTab));
p->symbol = symbol;
p->address = address;
p->next = NULL;
if (size == 0) {
first = p;
last = p;
} else {
last->next = p;
last = p;
}
size++;
return p;
}
struct SymbTab *Search(char *symbol) {
struct SymbTab *p = first;
while (p != NULL) {
if (strcmp(p->symbol, symbol) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
void Display() {
int i;
struct SymbTab *p;
p = first;
printf(" SYMBOL\tADDRESS ");
for (i = 0; i < size; i++) {
printf("%s\t%d ", p->symbol, p->address);
p = p->next;
}
}
void main() {
int op;
char la[10];
do {
printf(" SYMBOL TABLE IMPLEMENTATION ");
printf(" 1.INSERT 2.DISPLAY 3.SEARCH 4.END ");
printf(" Enter your option: ");
scanf("%d", &op);
switch (op) {
case 1:
printf(" Enter the symbol: ");
scanf("%s", la);
int address;
printf("Enter the address: ");
scanf("%d", &address);
Insert(la, address);
printf(" Symbol inserted ");
break;
case 2:
Display();
break;
case 3:
printf(" Enter the symbol to be searched: ");
scanf("%s", la);
struct SymbTab *result = Search(la);
printf(" Search Result:");
if (result != NULL) {
printf(" The symbol is present ");
} else {
printf(" The symbol is not present ");
}
break;
case 4:
exit(0);
}
} while (op < 4);
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
