Donoven Rally
Donoven Rally

Reputation: 1700

using array created in one function in another fucntion

I have a function in which i am reading a file with products and price of each product, and i am storing products in array and prices in another array like this:

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);
            }
        }
    }
}

The problem is that now i want to create a function that uses this two arrays ("Buy" function). the function will get a number and than gegt the price from the prices array and do something with it in the main() function. how can i use the values in the prices array in a different function?

Upvotes: 0

Views: 69

Answers (1)

Btc Sources
Btc Sources

Reputation: 2041

You can do it just by passing the arrays to the function and then index your item:

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]
}

And you can call your function like:

buy(prices);

Since type * is a pointer as type []. type your_var[] it's a pointer to a memory zone decided at compile time, so it is a pointer.

Upvotes: 1

Related Questions