c# 在C中向哈希表添加字符串和值[duplicate]

i2loujxw  于 2022-12-25  发布在  C#
关注(0)|答案(1)|浏览(155)
    • 此问题在此处已有答案**:

Why does a pointer to array need to be cast before being passed as parameter to a function with array type argument?(3个答案)
1小时前关闭。
我试图添加一个人和数字到哈希表,但当我添加这些值时,我得到了不兼容的指针类型传递'char *[20]'到类型'char *'的参数错误。
在将customer_number赋给索引时,我还得到了一个EXC_BAD_ACCESS(代码= 1,地址= 0x140)。

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

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

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

    list[index]->customer_number = customer_number;
    strcpy(list[index]->first_name, first_name);
    hash_table[index]=customer_number;
}

int main(void)
{
    insert("Chris", 9999);
    return 0;
}

当insert传递了名和phone_number时,我希望将它们添加到散列中。

iyfjxgzm

iyfjxgzm1#

这里有很多问题。您需要再次查看指针和缓冲区溢出...

#define CUSTOMER_NAME_MAX_LEN 20

typedef struct
{
    char first_name[CUSTOMER_NAME_MAX_LEN + 1];
    int customer_number;
} Customer;

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

int calculate_hash(int customer_number) {
  return 3;
}

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

    list[index].customer_number = customer_number;
    list[index].first_name[CUSTOMER_NAME_MAX_LEN] = 0;     // Avoid buffer overflow.
    strncpy(list[index].first_name, first_name, CUSTOMER_NAME_MAX_LEN);
    hash_table[index]=customer_number;
}

int main(void)
{
    insert("Chris", 9999);
    printf("%s %i\n", list[3].first_name, list[3].customer_number);
    return 0;
}

// Outputs Chris 9999

相关问题