gpt4 book ai didi

尝试使用指针打印值时 c 程序失败

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:16 25 4
gpt4 key购买 nike

当我试图从程序失败的数组中获取值时,我还没有收到任何错误。该程序包含一个函数,用于从文件中读取产品并将它们存储在类型为 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));

}

程序将从文件中打印出所有产品,但由于某种原因,程序的最后一行失败了。知道为什么吗?

最佳答案

我觉得,你需要改变

 printf("%s", *(ptr_to_products[2].name));

printf("%s", ptr_to_products[2].name);

因为 %s 需要一个 pointer-to-null-terminated char 数组。

关于尝试使用指针打印值时 c 程序失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com