c++ - 如何在c/c++中使用指针传递结构数组? [英] How to pass an array of struct using pointer in c/c++?

查看:32
本文介绍了c++ - 如何在c/c++中使用指针传递结构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 代码中,我坚持将结构数组传递给函数,这是类似于我的问题的代码:

<前>类型定义结构{整数 x;输入 y;字符 *str1;字符 *str2;}结构1;void processFromStruct1(Struct1 *content[]);int main(){结构 1 mydata[]={ {1,1,"black","cat"},{4,5,"red","bird"},{6,7,"brown","fox"},};processFromStruct1(mydata);//如何?!??找不到正确的语法返回0;}void processFromStruct1(Struct1 *content[]){printf("%s", content[1]->str1);//如果我想打印'red',这样对吗?...}

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

<前>错误 C2664:processFromStruct1":无法将参数 1 从Struct1 [3]"转换为Struct1 *[]"1> 指向的类型是不相关的;转换需要 reinterpret_cast、C-style cast 或 function-style cast

如何解决这个问题?tnx.

解决方案

你几乎已经拥有了,要么这个

void processFromStruct1(Struct1 *content);

或者这个

void processFromStruct1(Struct1 content[]);

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

content[1]->str1

到这里

content[1].str1

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

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.

解决方案

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.

这篇关于c++ - 如何在c/c++中使用指针传递结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆