【问题标题】:Pass structure array to function using pointers使用指针将结构数组传递给函数
【发布时间】:2016-09-18 23:15:35
【问题描述】:

我正在尝试发送一个结构数组作为参考,但由于某种原因我无法让它工作,因为它可以作为值传递但不能作为参考 (&)

这是我的代码:

#include <stdio.h>
#include <string.h>

struct mystruct {
    char line[10];
};

void func(struct mystruct record[])
{
    printf ("YES, there is a record like %s\n", record[0].line);
}

int main()
{
    struct mystruct record[1];
    strcpy(record[0].line,"TEST0");
    func(record);    
    return 0;
}

我以为只有调用函数 func(&record) 并将 func 函数参数更改为“struct mystruct *record[]”才能工作......但它没有。

请帮忙。

【问题讨论】:

  • “不起作用”,不是对您遇到的问题的非常有用的描述。请告诉我们你得到了什么输出。
  • 当我尝试引用 this 时,错误有点奇怪,但就是这样:
  • C 没有引用传递,一切都是值传递。但是func(record) 已经将record 数组作为指针传递。也就是说,它已经是您想要的“引用”(它没有复制整个结构数组)。
  • edit 您的问题包括您遇到的具体错误。此外,您不需要在标题中添加标签。我们有标签。
  • 了解数组和指针以及隐式转换。任何好的 C 书都应该详细说明。首先:不要像“按引用传递”那样思考,即使 iff 你也知道这不是实际发生的情况。想想“pass-by-pointer”(顺便说一句,少了 2 个字母)

标签: c function struct pass-by-reference


【解决方案1】:

我认为你的指针和参考概念混淆了。

func(&amp;record) 将传递变量记录的地址而不是引用。

传递指针

#include <stdio.h>
#include <string.h>

struct mystruct {
    char line[10];
};

void func(struct mystruct * record)
{
    printf ("YES, there is a record like %s\n", record[0].line);
    // OR
    printf ("YES, there is a record like %s\n", record->line);
}

int main()
{
    struct mystruct record[1];
    strcpy(record[0].line,"TEST0");
    func(record); // or func(&record[0])
    return 0;
}

如果你必须通过引用,试试这个

#include <stdio.h>
#include <string.h>

struct mystruct {
    char line[10];
};

void func(struct mystruct & record)
{
    printf ("YES, there is a record like %s\n", record.line);
}

int main()
{
    struct mystruct record[1];
    strcpy(record[0].line,"TEST0");
    func(record[0]);
    return 0;
}

更新

为了解决下面的评论,

  • 引用在纯 C 中不可用,仅在 C++ 中可用
  • 原始代码中的“故障”是struct mystruct record[],应该是struct mystruct &amp; record

【讨论】:

  • 哦,是的,这正是我要找的,指针的第一个选项,我把谈论引用的东西混在一起了,因为这些指针可以帮助你模拟同样的事情。谢谢
  • 这个问题被标记为c,所以没有参考。您只能在 c++ 中获得参考。
  • C 不支持引用。而且您没有指出问题代码中的错误。
  • 原代码是正确的,没有错误。 struct mystruct record[] 的含义与 struct mystruct * record 完全相同,作为函数参数。
猜你喜欢
  • 2021-11-02
  • 2019-05-03
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多