1

I want to make a function that multiplies each element in two arrays and store it in the new array.

For example: amount[i] = price[i] * quantity[i];

My code doesn't work. Here is my code:

#include <stdio.h>

void extend(float[], float[], double[]);

int main(void) {

    float price[10] = { 10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98 };
    float quantity[10] = { 4, 8.5, 6, 8.35, 9, 15.3, 3, 5.4, 2.9, 4.8 };
    double amount[10] = { 0 };
    extend(price, quantity, amount);
    for (int i = 0; i < 10; i++) {
        printf("%f ", amount[i]);
    }
   return 0;
}

void extend(float PRICE[], float QUANTITY[], double amount[]) {
    for (int i = 0; i < 10; i++) {
        amount[i] = PRICE[i] * QUANTITY[i];
    }
}

Please let me know which part is wrong.

Yun
  • 3,056
  • 6
  • 9
  • 28
haeye2014
  • 11
  • 1
  • code looks fine, what does not work? – tstanisl Sep 20 '21 at 11:55
  • 4
    "doesn't work" is never a good problem description. Please give the exact expected behaviour vs actual behaviour. It's not obvious why you think the code is not working. – kaylum Sep 20 '21 at 11:55
  • maybe just put `puts("");` just before end of `main()`. It will make the result more visually pleasing – tstanisl Sep 20 '21 at 11:56
  • https://ideone.com/QVbxm7 looks good. What is your output and what did you do to get it? – mch Sep 20 '21 at 11:56
  • You may need to add a `putchar('\n');` or `puts("");` or `fflush(stdout)` after the output loop to get the output to actually show up on your console. Standard output is usually *line buffered*, meaning nothing's sent to the output device until the buffer's full or a newline is sent. – John Bode Sep 20 '21 at 13:41
  • I'm not sure that any part is wrong, as such. The output could be tidied up, as noted by others. To answer your headline question: you cannot really pass an array into a C function. You can pass the address of the first member in an array, and the function can then read multiple items starting at that address, but you still need to know how many items are in that array. In your case, you have a hard-coded `10` in `extend()`. Another option would be to have passed it in as a parameter. – Tim Randall Sep 20 '21 at 13:45
  • Does this answer your question? [Passing array as parameter](https://stackoverflow.com/questions/20036549/passing-array-as-parameter) – Tim Randall Sep 20 '21 at 13:48

1 Answers1

0

code is work on codeblocks. No any error.enter image description here