我正在尝试实现函数 (1) 以在结构数组中按名称查找特定产品。p_array 是包含 n 个产品的结构数组,search_key 是指向具有搜索结构名称的字符串的指针 cmp 是指向我已实现的另一个函数 (2) 的指针。
/* (1) */
const Product* findProduct(const Product* p_array, const char* search_key, int (*cmp)(const void*, const void*))
{
return bsearch(&search_key, p_array, 100, sizeof(Product), cmp);
}
/* (2) */
int compareAlpha(const void* a, const void* b)
{
const struct Product *shop_a = a;
const struct Product *shop_b = b;
int ret = strcmp(shop_a->name,shop_b->name);
return ret;
}
我有以下问题:
- 我想不出办法找出 p_array 的长度
- 启动程序导致分段错误,我不知道为什么
我的主要功能是:
void printProducts(Product* array)
{
int i = 0;
while(array[i].name[0] != 0)
{
printf("product: %s\tprice: %f\t in stock: %d\n", array[i].name, array[i].price, array[i].in_stock);
i++;
}
}
int main()
{
Product array[6] = {
{"peanut butter", 1.2, 5},
{"cookies", 12.3, 23},
{"cereals", 3.2, 12},
{"bread", 2.7, 12},
{"butter", 4.2, 5},
{"\0", 0.0, 0}
};
qsort(array, 5, sizeof(Product), compareAlpha);
printf("sorted lexically:\n");
printProducts(array);
const Product* search = findProduct(array, "cookies", compareAlpha);
if(search)
{
printf("Found product:\n");
printf("%s\n", search->name);
}
qsort(array, 5, sizeof(Product), compareNum);
printf("sorted by in stock:\n");
printProducts(array);
return 0;
}
想要的输出是
sorted lexically:
product: bread price: 2.700000 in stock: 12
product: butter price: 4.200000 in stock: 5
product: cereals price: 3.200000 in stock: 12
product: cookies price: 12.300000 in stock: 23
product: peanut butter price: 1.200000 in stock: 5
Found product:
cookies
Product not found!
sorted by in stock:
product: cookies price: 12.300000 in stock: 23
product: bread price: 2.700000 in stock: 12
product: cereals price: 3.200000 in stock: 12
product: butter price: 4.200000 in stock: 5
product: peanut butter price: 1.200000 in stock: 5