How to pass an array of structure using a pointer in c / C ++?

in C code I am stuck to pass a struct array to a function, here is the code that looks like my problem:

  typedef struct
 {
    int x;
    int y;
    char * str1;
    char * str2;
 } Struct1;

 void processFromStruct1 (Struct1 * content []);
 int main ()
 {
     Struct1 mydata [] =
     {{1,1, "black", "cat"},
       {4,5, "red", "bird"},
       {6,7, "brown", "fox"},
     };

     processFromStruct1 (mydata); // how?! ??  can't find correct syntax

     return 0;
 }

 void processFromStruct1 (Struct1 * content [])
 {
     printf ("% s", content [1] -> str1); // if I want to print 'red', is this right?
         ...
 }

A compilation error in msvc looks something like this:

  error C2664: 'processFromStruct1': cannot convert parameter 1 from 'Struct1 [3]' to 'Struct1 * []'
 1> Types pointed to are unrelated;  conversion requires reinterpret_cast, C-style cast or function-style cast

How to solve this? Hh

+4
source share
5 answers

You almost had it, or it

void processFromStruct1(Struct1 *content); 

or

 void processFromStruct1(Struct1 content[]); 

and as Alok points out in the comments, change this

 content[1]->str1 

to that

 content[1].str1 

Your array is an array of structures, not an array of pointers, so when you select a specific structure using [1], there is no need to dereference it further.

+10
source

Try

 processFromStruct1( & mydata[ i ] ); // pass the address of i-th element of mydata array 

and method

 void processFromStruct1(Struct1 *content ) { printf("%s", content->str1); ... } 

(The second part is already noted by John Knoller and Alok).

+2
source
John Knoller gave excellent syntax, I am trying to explain some basic things, I hope that in the future this will lead to your confusion. This is very similar to passing a pointer to a function in C. Of course, struct is also a pointer,

so we can pass the value in two ways 0. Through the pointer 0. Through the array (since we use the struct array)

therefore, the problem is simple now, you must specify the data type of the variable, as in regular pointers, here the data type is defined by the user (this means struct) Struct1, then the variable name, this variable name can be a pointer or an array name (choose a compatible method).

+1
source

This works for me. Changed C ++ style structures.

 struct Struct1 { int x; int y; char *str1; char *str2; }; Struct1 mydata[]= { {1,1,"black","cat"}, {4,5,"red","bird"}, {6,7,"brown","fox"}, }; void processFromStruct1(Struct1 content[]); int main() { processFromStruct1(&mydata[1]); return 0; } void processFromStruct1(Struct1 content[]) { printf("%s",content->str1); } 

output: red

+1
source

You can try the prototype as void processFromStruct1(Struct1 content[]); and then the ad should look like void processFromStruct1(Struct1 content[]) .

-1
source

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


All Articles