1

I'm trying to add a persons and number to a hash table, but when I'm adding these values I get the incompatible pointer types passing 'char *[20]' to parameter of type 'char *' error.

I'm also getting an EXC_BAD_ACCESS (code=1, address=0x140) when assigning the customer_number to the index.


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;
}

When the insert is passed a first name and phone_number, I want these to be added to the hash.

Morris
  • 11
  • 2

1 Answers1

0

There are a number of issues here. You need to look again at pointers and buffer overflows...

#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
Simon Goater
  • 759
  • 1
  • 1
  • 7
  • If you're going to use `strncpy()`, you have to make sure the result gets 0-terminated. It won't in this if the name is 20 characters or more... – Shawn Dec 24 '22 at 22:23
  • Thank you for your help, I'm starting to see where I'm going wrong. – Morris Dec 24 '22 at 22:30
  • @Shawn It does get null terminated because on the previous line I set the last element to zero. – Simon Goater Dec 25 '22 at 12:27