You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C语言哈希表中添加字符串与数值时遇指针及访问错误求助

哈希表插入操作的错误修复方案

错误1:指针类型不兼容

原结构体中char *first_name[20]定义的是20个char指针的数组,而strcpy的第一个参数需要char*类型的字符串首地址。直接传递list[index]->first_name时,实际传递的是指针数组的地址(类型为char**),与strcpy参数类型不匹配,导致编译错误。

修复方法:将结构体中的姓名成员改为字符数组,直接存储字符串:

typedef struct
{
    char first_name[20]; // 改为字符数组,用于存储姓名
    int customer_number;
} Customer;

错误2:EXC_BAD_ACCESS内存访问错误

list是Customer*类型的数组,初始化时所有元素都是未赋值的野指针。直接通过list[index]->customer_number访问内存时,相当于操作非法内存地址,触发内存访问错误。

修复方法:插入前为list[index]分配内存:

void insert(char *first_name, int customer_number)
{
    int index = calculate_hash(customer_number);

    // 为当前索引的Customer结构体分配内存
    list[index] = malloc(sizeof(Customer));
    if (list[index] == NULL) {
        perror("malloc failed");
        return;
    }

    list[index]->customer_number = customer_number;
    // 用strncpy避免缓冲区溢出,更安全
    strncpy(list[index]->first_name, first_name, sizeof(list[index]->first_name) - 1);
    // 手动添加字符串结束符,保证是合法C字符串
    list[index]->first_name[sizeof(list[index]->first_name) - 1] = '\0';
    hash_table[index] = customer_number;
}

补充:实现calculate_hash函数

原代码缺少哈希函数实现,补充一个简单的取模实现:

int calculate_hash(int customer_number)
{
    // 取模确保索引在0-9范围内
    return customer_number % 10;
}

完整修正代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char first_name[20];
    int customer_number;
} Customer;

Customer *list[10];
int hash_table[10];

int calculate_hash(int customer_number)
{
    return customer_number % 10;
}

void insert(char *first_name, int customer_number)
{
    int index = calculate_hash(customer_number);

    list[index] = malloc(sizeof(Customer));
    if (list[index] == NULL) {
        perror("malloc failed");
        return;
    }

    list[index]->customer_number = customer_number;
    strncpy(list[index]->first_name, first_name, sizeof(list[index]->first_name) - 1);
    list[index]->first_name[sizeof(list[index]->first_name) - 1] = '\0';
    hash_table[index] = customer_number;
}

int main(void)
{
    insert("Chris", 9999);
    // 验证插入结果
    int idx = calculate_hash(9999);
    printf("Name: %s, Customer Number: %d\n", list[idx]->first_name, list[idx]->customer_number);
    
    // 释放内存避免泄漏
    free(list[idx]);
    return 0;
}

内容的提问来源于stack exchange,提问作者Morris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:15:47