如何在c/c ++中使用指针传递一个struct数组?

mhd*_*mhd 9 c parameters struct

在C代码中,我坚持将一个struct数组传递给一个函数,这里的代码类似于我的问题:

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?
        ...
}

msvc中的编译错误是这样的:

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

怎么解决这个?TNX.

Joh*_*ler 13

你几乎拥有它,或者这个

void processFromStruct1(Struct1 *content);
Run Code Online (Sandbox Code Playgroud)

或这个

void processFromStruct1(Struct1 content[]);
Run Code Online (Sandbox Code Playgroud)

并且,正如Alok在评论中指出的那样,改变这一点

content[1]->str1
Run Code Online (Sandbox Code Playgroud)

对此

content[1].str1
Run Code Online (Sandbox Code Playgroud)

你的数组是一个结构数组,而不是一个指针数组,所以一旦你用[1]选择一个特定的结构,就没有必要进一步取消引用它.

  • 和`content [1] - > str1`变成`content [1] .str1`. (6认同)
  • 他可能也希望通过一个长度. (5认同)