views:

221

answers:

3

Hi, in C code I'm stuck to pass an array of struct to a function, here's the code that resembles 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?
        ...
}

Compile error in msvc is 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? tnx.

+7  A: 

You almost had it, either this

void processFromStruct1(Struct1 *content);

or this

void processFromStruct1(Struct1 content[]);

and, as Alok points out in comments, change this

content[1]->str1

to this

content[1].str1

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

John Knoeller
and `content[1]->str1` becomes `content[1].str1`.
Alok
@Alok: good eye.
John Knoeller
He may also want to pass a length.
Matthew Flaschen
...which can be obtained by passing `sizeof(mydata)/sizeof(mydata[0])`, but only _before_ the function call
Adam Rosenfield
@Adam: ...or *after* the call, but not *in* the call :-).
Alok
@John @Alok: Thanks!!! I guess I was too self-complicating for this problem :)
mhd
+2  A: 

Try

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

and the method to

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

(2nd part already noted by John Knoeller and Alok).

ArunSaha
Then one can't index that pointer with 1, one can only use 0. Not sure if this is what the OP wants. Also the type is wrong.
Alok
OK, now I am happy with the answer. +1.
Alok
@Alok: Thank you.
ArunSaha
+1  A: 

John Knoeller gave the perfect syntax , I am trying to explain some basic things, I hope that it willsolve your confusions in future. This is very similar to passing pointer to a function in C. Of course struct is also a pointer,

so we can pass the value in 2 ways 0. Via pointer 0. Via array ( since we are using array of struct )

so the problem is simple now , You have to give the data type of a variable as we do in normal pointers , here the data type is user-defined ( that means struct ) Struct1 then variable name, that variable name can be pointer or array name ( choose a compatible way ).

abubacker