Passing a struct array with typedef into a function

I need help programming in C. I have the following situation:

struct Product { int code; char *name; char *spec; int quantity; float price; }; typedef struct Product products[8]; products product = { {100, "Mouse", "Ottico", 10, 8.30}, {101, "Tastiera", "Wireless", 6, 15.50}, {102, "Monitor", "LCD", 3, 150.25}, {103, "Webcam", "USB", 12, 12.00}, {104, "Stampante", "A Inchiostro", 6, 100.00}, {105, "Scanner", "Alta Risoluzione", 9, 70.50}, {106, "Router", "300 Mbps", 10, 80.30}, {107, "Lettore Mp3", "10 GB", 16, 100.00} }; 

Please ignore the use of the Italian language above.

I would like to pass an array of structures named "product" to a function. For example, if I wanted to do something like

 product[1].name = "Computer" 

But inside the function, how should I do it? I would like to know how to call this function from main () and how to write a prototype in my header file.

Thanks in advance for your help.

EDIT

I give you this test program. This does not work, and in principle there is no way to call. It just doesn't compile.

 #include <stdio.h> #include <stdlib.h> void test(Card *card); int main() { struct Card { char *type; char *name; }; typedef struct Card cards[2]; cards card = {{"Hi", "Hi"}, {"Foo", "Foo"}}; return 0; } void test(Card *card) { printf("%s", card[1].type); } 
+6
source share
3 answers

Here:

 void foo(struct Product *bla) { bla[1].name = "Computer"; } 

or using an alias of your type

 void foo(products bla) { bla[1].name = "Computer"; } 

then call the function as follows:

 foo(product); 
+6
source

Since you have a typedef (which, incidentally, lacks the struct keyword in your example), you can simply use this type in the function prototype:

 void func(products p); 

The function that performs the specific operation that you requested can be:

 void func(products p) { p[1].name = "Computer"; } 

You can call it like this:

 func(product); 

From any place where the product is in scope.

+2
source
 typedef struct tag_Product { int code; char *name; char *spec; int quantity; float price; } PRODUCT; PRODUCT products[8] = { {100, "Mouse", "Ottico", 10, 8.30}, {101, "Tastiera", "Wireless", 6, 15.50}, {102, "Monitor", "LCD", 3, 150.25}, {103, "Webcam", "USB", 12, 12.00}, {104, "Stampante", "A Inchiostro", 6, 100.00}, {105, "Scanner", "Alta Risoluzione", 9, 70.50}, {106, "Router", "300 Mbps", 10, 80.30}, {107, "Lettore Mp3", "10 GB", 16, 100.00} }; void MyFunction(PRODUCT *pProduct) { pProduct->code = 0; // sample } void main() { MyFunction(&products[2]); // sample } 
0
source

Source: https://habr.com/ru/post/907335/


All Articles