因此,我一直在尝试理解在不使用malloc链表的情况下定期定义的结构与使用malloc的结构之间的区别。
我现在遇到的问题是,试图通过结构(pi)进行搜索,以找到每个成本比搜索中输入的成本更高的零件号。到目前为止,这是我的全部计划。我为每个部分添加了评论。
我只是不确定我应该如何搜索每个结构,将其价格与搜索价格进行比较。
#include <stdio.h>
#include <stdlib.h>
struct Item {
int quantity;
float cost;
char partNum[10];
struct Item *next;
};
void printItem(struct Item* pi);
void enterItem(struct Item* pi);
char search [100];
void main(int argc, char* argv[])
{
struct Item *pi;
struct Item *head;
int done = 0;
int i,j;
char choice;
// ENTERING ITEM INTO THE STRUCTURE
head = NULL;
while (!done) {
printf("Enter another item? (y/n)");
choice = getchar();
if (choice == 'y' || choice == 'Y') {
pi = (struct Item *)malloc(sizeof(struct Item));
enterItem(pi);
pi->next = head;
head = pi;
} else {
done = 1;
}
}
// SEARCHING FOR ITEM BY PRICE
printf("Enter a price to find all items more expensive, or type 'exit':");
while (strcmp(search, "exit") !=0) {
gets(search);
for (j = 0; j<i ; i++) {
if (strcmp(pi[j].cost, search) ==0) {
printItem(pi);
pi = pi->next;
}
}
}
}
getchar();
getchar();
}
// FUNCTION FOR PRINTING STRUCTURE ITEM
void printItem(struct Item* pi) {
printf("Quantity: %dn", pi->quantity);
printf("Cost: $%.2fn", pi->cost);
printf("Part # %sn", pi->partNum);
printf("nn");
}
// FUNCITON FOR ENTERING IN NEW ITEM
void enterItem(struct Item* pi) {
printf("Quantity? ");
scanf("%d", &pi->quantity);
printf("Cost? ");
scanf("%f", &pi->cost);
getchar(); //need to clear out the carriage return from typeing in the cost
printf("Part Number? ");
gets(pi->partNum);
}
错误的是使用strcmp
比较字符串(search
变量)和浮点(cost
变量)。这不会给你想要的输出。
相反,让我们使用-1
来指示exit
,因为解析字符串并将其转换为float是不主题的。从head
开始迭代,直到找到NULL
,并比较每个项目的价格。
float price;
struct Item *it = head;
printf("Enter a price to find all items more expensive, or type '-1' to exit:");
scanf("%f", price);
// check price for the 'exit' -- compare with -1
while (it != NULL) {
if (it->cost > price)
printItem(pi);
it = it->next;
}