C 向结构数组传递指针
我一直在做一项图书作业,希望能得到一些帮助,但我遇到了一些问题。我的程序编译没有问题,但当我运行它时,我得到C 向结构数组传递指针,c,pointers,C,Pointers,我一直在做一项图书作业,希望能得到一些帮助,但我遇到了一些问题。我的程序编译没有问题,但当我运行它时,我得到 First time through: (null) After: 0000000 First time through: (null) After: 1111111 当我插入一个散列时,它会检查数组值是否已经被赋值。如果是,它将打印“已检测到冲突”,并创建一个新节点并将其链接到上一个节点。现在它看起来像是一个自动变量,即使我给它传递了一个指针 我很确定这与我如何声明我的结构数组并将它
First time through: (null)
After: 0000000
First time through: (null)
After: 1111111
当我插入一个散列时,它会检查数组值是否已经被赋值。如果是,它将打印“已检测到冲突”,并创建一个新节点并将其链接到上一个节点。现在它看起来像是一个自动变量,即使我给它传递了一个指针
我很确定这与我如何声明我的结构数组并将它们传递到insert_散列有关,但我似乎无法理解。感谢您的帮助
struct hash_node
{
char *data;
struct hash_node *next;
};
struct hash_node *create_table(int size);
unsigned int hash(const char *str);
void insert_hash(const char *str, const char *value, struct hash_node *h);
int
main(void)
{
struct hash_node *table = create_table(101);
insert_hash("testing", "0000000", table);
insert_hash("testing", "1111111", table);
}
struct hash_node
*create_table(int size)
{
struct hash_node *table = calloc(size, sizeof(*table));
if(!table)
{
fprintf(stderr, "Unable to allocate memory\n");
return NULL;
}
return table;
}
unsigned int
hash(const char *str)
{
unsigned int c, hash;
while ((c = *str++))
{
hash += c;
}
hash = hash % 100;
return hash;
}
void
insert_hash(const char *str, const char *value, struct hash_node *h)
{
int temp = hash(str);
printf("First time through: %s\n", h[temp].data);
if (h[temp].data)
{
fprintf(stderr, "Collision detected\n");
struct hash_node *node = calloc(1, sizeof(*node));
if (!node)
{
fprintf(stderr, "Unable to allocate memory\n");
return;
}
node -> data = malloc(strlen(value) + 1);
strncpy(node -> data, value, strlen(value) + 1);
node->next = NULL;
h[temp].next = node;
}
else
{
h[temp].data = malloc(strlen(value) + 1);
strncpy(h[temp].data, value, strlen(value) + 1);
}
printf("After: %s\n", h[temp].data);
}
hash
函数错误
unsigned int
hash(const char *str)
{
unsigned int c, hash; //<--- not initialized
while ((c = *str++))
{
hash += c;
}
hash = hash % 100;
return hash;
}
然后我得到
首次通过:(空)
之后:0000000
首次通过:0000000
检测到碰撞
之后:0000000
编辑 在发生冲突的情况下,您也没有正确附加新节点。你 首先必须找到列表的末尾,然后在末尾追加新节点 名单上的:
node *tail = h[temp].next;
while(tail->next)
tail = tail->next;
struct hash_node *node = calloc(1, sizeof(*node));
...
tail->next = node;
或者,您可以在列表的开头预结束新节点
struct hash_node *node = calloc(1, sizeof(*node));
...
node->next = h[temp].next;
h[temp].next = node;
我想你是指struct hash_node*table=calloc(size,sizeof(table));或trct hash_node**table=calloc(size,sizeof(*table));“我的程序编译时没有问题…”嗯,没有。请尝试在启用警告的情况下编译。对于gcc或clang,请使用
-Wall
。您还需要描述您遇到的问题。我认为您显示的输出没有任何问题。感谢您的反馈。我启用了Wall,但当我添加所有其他标志时,我看到了错误。@AmiNoprintf(“第一次通过:%s\n”,h[temp].data)代码>是未定义的行为,因为h[temp]。数据为NULL
,它有时可能打印(NULL)
,有时可能会崩溃。感谢您的帮助!
struct hash_node *node = calloc(1, sizeof(*node));
...
node->next = h[temp].next;
h[temp].next = node;