drm*_*irk 0 c struct heap-memory calloc dynamic-memory-allocation
我正在尝试使用以下代码编写一个非常简单的哈希表:
#include <stdio.h>
#include <string.h>
#define SIZE 10
typedef struct {
char *first_name;
char *last_name;
} Employee;
typedef struct {
Employee *table;
} Hashtable;
void initHashtable(Hashtable *ht) {
ht->table = (Employee *)calloc(SIZE, sizeof(Employee));
}
int hashKey(char *key) {
int length = strlen(key);
return length % SIZE;
}
void put(Hashtable *ht, Employee emp, char *key) {
int hashedKey = hashKey(key);
ht->table[hashedKey] = emp;
}
Run Code Online (Sandbox Code Playgroud)
我可以通过执行以下操作插入元素:
int main(int argc, char const *argv[]) {
Employee e1;
e1.first_name = "John";
e1.last_name = "Doe";
Hashtable ht;
initHashtable(&ht);
put(&ht, e1, "Doe");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但我想修改“put”函数,因此当我尝试插入某些内容时,它会检查该索引是否为空。如果为空则返回一些消息,如果不是则插入该索引。如同:
void put(Hashtable *ht, Employee emp, char *key) {
int hashedKey = hashKey(key);
if (ht->table[hashedKey] != 0) {
printf("Employee is in that index!\n");
} else {
ht->table[hashedKey] = emp;
}
}
Run Code Online (Sandbox Code Playgroud)
但这个“if 语句”不起作用。所以,我尝试了 0 和 NULL。然后我尝试像这样进行铸造:
if(ht->table[hashedKey] != (Employee *)0)
Run Code Online (Sandbox Code Playgroud)
和
if(ht->table[hashedKey] != (Employee)0)
Run Code Online (Sandbox Code Playgroud)
什么都不起作用。我的问题是我知道 calloc 初始化为 0,零。那么如果是 struct,calloc 用什么来初始化呢?
我的问题是我知道 calloc 初始化为 0,零。那么如果是 struct,calloc 用什么来初始化呢?
calloc完全不知道你将如何使用内存。它只是为您提供您请求的金额,并将所有位设置为零。看一下它的原型:
void * calloc(size_t num, size_t size)
Run Code Online (Sandbox Code Playgroud)
参数num和size是唯一具有的信息calloc。
| 归档时间: |
|
| 查看次数: |
1546 次 |
| 最近记录: |