我有一个功能,我正在阅读包含每个产品的产品和价格的文件,我将数据和价格存储在另一个数组中,如下所示:
Canvas
问题是现在我想创建一个使用这两个数组的函数(" Buy"函数)。该函数将得到一个数字,而不是TDbgrid
数组中的价格,并在void displayProducts(int balance){
printf("-----------Available Products-----------\n");
putchar('\n');
int row=0;
const char *products[8];
int prices[8];
char line[MAX_LINE_SIZE + 1]; // ptr to the current input line
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){
row++;
products[row] = name;
prices[row] = price;
printf("%d) %s price %d\n", row, products[row], prices[row]);
}
next_item = strtok_s(NULL, ",;", &next_ptr);
}
}
}
}
函数中对其执行某些操作。
如何在不同函数中使用prices
数组中的值?
答案 0 :(得分:1)
只需将数组传递给函数然后索引项目即可:
void buy(int * my_int_array_prices)
{
//Here, this would return you the value of the second item
//in your array: my_int_array_prices[1]
}
您可以将您的功能称为:
buy(prices);
由于type *
是指针type []
。 type your_var[]
它是指向编译时决定的内存区域的指针,因此它是一个指针。