当我尝试从数组中获取值时程序失败,我还没有收到任何错误。该程序包含一个从文件中读取产品并将其存储在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));
}
程序将打印出文件中的所有产品,但由于某种原因,程序的最后一行失败。知道为什么吗?
答案 0 :(得分:2)
我想,你需要改变
printf("%s", *(ptr_to_products[2].name));
到
printf("%s", ptr_to_products[2].name);
因为%s
需要一个指针到空终止的 char
数组。
答案 1 :(得分:2)
products
数组中的所有指针都指向line
数组。这有两个问题:
此数组是displayProducts
的本地数组,并在函数返回时被销毁。
products
的每个元素都有指向同一行数组的指针。因此,当您从文件中读取新行时,您将覆盖products
之前元素中保存的值。
在将name
保存到products[row]
之前,您需要在堆中复制 char *name_copy = malloc(strlen(name)+1);
strcpy(name_copy, name);
products[row].name = name_copy;
。
printf("%s", ptr_to_products[2].name);
您还需要修复打印代码,如另一个答案:
<style>
#RegisterForm {
display: block;
position: relative;
}
#spinner {
display: none;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-align: center;
background: url(spinner.gif) no-repeat center #fff;
padding: 10px;
font: normal 16px Tahoma, Geneva, sans-serif;
border: 1px solid #666;
z-index: 2;
opacity: 0.75;
}
</style>