C程序设计语言 (第二版) 练习 6-5
练习 6-5 编写函数undef,它将从由lookup和install维护的表中删除一个变量及其定义。
注意:代码在win32控制台运行,在不同的IDE环境下,有部分可能需要变更。
IDE工具:Visual Studio 2010
文章来源地址https://www.toymoban.com/news/detail-812534.html
代码块:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASHSIZE 101
struct nlist {
struct nlist *next;
char *name;
char *defn;
};
static struct nlist *hashtab[HASHSIZE];
unsigned hash(char *s) {
unsigned hashval;
for(hashval = 0; *s != '\0'; s++){
hashval = *s + 31 * hashval;
}
return hashval % HASHSIZE;
}
char *_strdup(char *s){
char *p;
p = (char *) malloc(strlen(s) + 1);
if (p != NULL){
strcpy(p, s);
}
return p;
}
struct nlist *lookup(char *s){
struct nlist *np;
for(np = hashtab[hash(s)]; np != NULL; np = np->next){
if (strcmp(s, np->name) == 0){
return np;
}
}
return NULL;
}
struct nlist *install(char *name, char *defn){
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL){
np = (struct nlist *) malloc(sizeof(*np));
if(np == NULL || (np->name = _strdup(name)) == NULL){
return NULL;
}
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
else{
free((void *) np->defn);
}
if ((np->defn = _strdup(defn)) == NULL){
return NULL;
}
return np;
}
int undef(char * name){
struct nlist * np1, * np2;
if ((np1 = lookup(name)) == NULL){
return 1;
}
for(np1 = np2 = hashtab[hash(name)]; np1 != NULL; np2 = np1, np1 = np1->next){
if (strcmp(name, np1->name) == 0){
if(np1 == np2){
hashtab[hash(name)] = np1->next;
}
else{
np2->next = np1->next;
}
free(np1->name);
free(np1->defn);
free(np1);
return 0;
}
}
return 1;
}
int main(){
system("pause");
return 0;
}
文章来源:https://www.toymoban.com/news/detail-812534.html
到了这里,关于C //练习 6-5 编写函数undef,它将从由lookup和install维护的表中删除一个变量及其定义。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!