【发布时间】:2014-11-02 14:58:46
【问题描述】:
所以我一直在尝试了解不使用使用 malloc 的 malloc 链表的定期定义结构之间的区别。
我现在遇到的问题是尝试搜索结构 (pi) 以查找成本大于搜索中输入的成本的每个零件号。到目前为止,这是我的整个程序。我为每个部分添加了 cmets。
我只是不确定我应该如何搜索每个结构以将其价格与搜索价格进行比较。
#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: %d\n", pi->quantity);
printf("Cost: $%.2f\n", pi->cost);
printf("Part # %s\n", pi->partNum);
printf("\n\n");
}
// 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);
}
【问题讨论】:
-
for (j = 0; j<i ; i++)是一个奇怪的 for 循环,尤其是考虑到i从未被初始化。 -
是的,我从另一段代码中添加了该部分,我必须搜索结构,而不是链接列表。所以我复制了它,希望我可以修改它来工作......没有走远。 @ooga
-
这一行:for (j = 0; j
-
这一行:pi = pi->next;需要移动到 if 代码块的右大括号之后,因此它会导致 pi 始终被步进到链表中的下一个条目
-
代码创建了一个循环链表,那么'for'循环如何知道何时停止搜索呢?由于变量 'i' 未设置为链表中的条目数,因此搜索停止的时间完全取决于未初始化变量 'i' 中的(随机)值
标签: c pointers search linked-list malloc