使用指针将结构数组传递给函数

Pass structure array to function using pointers

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

这是我的代码:

#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[]" 它才会起作用...但它没有。

请帮忙。

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

func(&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++ 中可用
  • 原代码中的'fault'是struct mystruct record[]应该是struct mystruct & record