【发布时间】:2015-05-22 22:08:21
【问题描述】:
当我尝试从数组中获取值时,我没有收到任何错误,但程序失败了。该程序包含一个从文件中读取产品并将它们存储在typedef structure item 类型数组中的函数。
程序是这样的:
item *displayProducts(int balance){
int row=0;
char line[MAX_LINE_SIZE + 1]; // ptr to the current input line
static item products[8];
FILE *fp;
fp = fopen("machinedata.txt", "r");
if (fp == NULL)
{
printf("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
while (fgets(line, MAX_LINE_SIZE, fp)) {
char *next_ptr = NULL;
char *next_item = strtok_s(line, ",;", &next_ptr);
while (next_item != NULL){
char *item_ptr = NULL;
char *name = strtok_s(next_item, "-", &item_ptr);
if (name == NULL)
{
fprintf(stderr, "Failed to scan name out of [%s]\n", next_item);
break;
}
int price;
next_item = strtok_s(NULL, " ,", &item_ptr);
//assert(next_item != NULL);
if (strcmp(name," ")){
if (sscanf(next_item, "%d", &price) != 1)
fprintf(stderr, "Failed to convert [%s] to integer\n", next_item);
else if (balance > price){
products[row].name = name;
products[row].price = price;
products[row].product_code = row + 1;
printf("%d) %s:%d\n",products[row].product_code, products[row].name, products[row].price);
row++;
}
next_item = strtok_s(NULL, ",;", &next_ptr);
}
}
}
fclose(fp);
return products;
}
void main( int argc, char *argv[]){
int *ptr_to_balance;
int balance = atoi(argv[2]);
ptr_to_balance = &balance;
item *ptr_to_products;
Init(argv[1], balance);
ptr_to_products = displayProducts(balance);
printf("%s", *(ptr_to_products[2].name));
}
程序将打印出文件中的所有产品,但由于某种原因,程序的最后一行失败了。知道为什么吗?
【问题讨论】:
-
欢迎来到 StackOverflow。然而,我们需要处理大量的代码!你能调试它直到你发现它出错的地方吗?您最终可能会自己回答问题,但如果没有,您将能够告诉我们哪里出了问题。但也要告诉我们症状,因为只是说“程序失败”并不能告诉我们实际出了什么问题。做这一切,你可能会从人们那里得到一些答案。
-
你能给我们项目结构吗?它会帮助我们
-
typedef struct item{ char* name; int product_code; int price; }item; -
发布的代码无法编译。它缺少一些关键项目,例如“#include”语句。请重新发布代码的可编译版本,以演示潜在问题。然后告诉我们问题的症状是什么,以便我们为您提供帮助。如目前所写,编译步骤引发 42 个警告和错误!!!编译时,启用所有警告,(对于 gcc 使用,至少需要 '-Wall -Wextra -pedantic')
-
在使用任何 'expected' 命令行参数之前,始终检查这样的参数是否存在,使用 main() 的 'argc' 参数。如果没有足够的参数(或参数类型错误),则打印“使用”语句并退出。