传递结构的数组用C [英] Passing an array of structs in C

查看:165
本文介绍了传递结构的数组用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在传递结构的数组给一个函数用C麻烦了。

我创建了结构像这样在主:

  INT的main()
{
    项目结构
    {
        字符code [10];
        字符描述[30];
        诠释股票;
    };    结构相关MyItems [10];
}

然后我访问它,如: MyItems [0] .stock = 10;

我想将它传递给像这样一个功能:

 的ReadFile(MyItems);

该函数应阅读阵列,并能够对其进行编辑。然后,我应该能够访问其他功能相同的数组。

我试过声明堆,但他们没有工作。
例如

 无效ReadFile的(结构项目[10])

我有一个看看周围其他的问题,但事情是他们全部完成不同,同类型定义和星号。我的老师并没有教我们尚未指针,所以我想什么,我知道做到这一点。

任何想法? :•

编辑:萨尔瓦托雷的答案工作后我固定我的原型:

 无效ReadFile的(结构项目[10]);


解决方案

 结构项目
{
    字符code [10];
    字符描述[30];
    诠释股票;
};无效ReadFile的(结构笔数[10])
{
    ...
}无效XXX()
{
    结构相关MyItems [10];
    ReadFile的(MyItems);
}

这在我的编译器效果很好。
您正在使用什么编译器?你有什么错误?

记得以前你的函数来声明结构或它永远不会工作。

I'm having trouble passing an array of structs to a function in C.

I've created the struct like this in main:

int main()
{
    struct Items
    {
        char code[10];
        char description[30];
        int stock;
    };

    struct Items MyItems[10];
}

I then access it like: MyItems[0].stock = 10; etc.

I want to pass it to a function like so:

 ReadFile(MyItems);

The function should read the array, and be able to edit it. Then I should be able to access the same array from other functions.

I've tried heaps of declarations but none of them work. e.g.

void ReadFile(struct Items[10])

I've had a look around for other questions, but the thing is they're all done different, with typedefs and asterisks. My teacher hasn't taught us pointers yet, so I'd like to do it with what I know.

Any ideas? :S

EDIT: Salvatore's answer is working after I fixed my prototype to:

void ReadFile(struct Items[10]);

解决方案

struct Items
{
    char code[10];
    char description[30];
    int stock;
};

void ReadFile(struct Items items[10])
{
    ...
}

void xxx()
{
    struct Items MyItems[10];
    ReadFile(MyItems);
}

This in my compiler works well. What compiler are you using? What error you got?

Remember to declare your struct before your functions or it will never work.

这篇关于传递结构的数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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