Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用指针将结构数组传递给函数_C_Function_Struct_Pass By Reference - Fatal编程技术网

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

C 使用指针将结构数组传递给函数,c,function,struct,pass-by-reference,C,Function,Struct,Pass By Reference,我试图发送一个结构数组作为引用,但由于某些原因,我无法让它工作,因为它可以传递值,但不能作为引用& 这是我的代码: #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].lin

我试图发送一个结构数组作为引用,但由于某些原因,我无法让它工作,因为它可以传递值,但不能作为引用&

这是我的代码:

#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++中使用 原始代码中的“错误”是struct mystruct记录[]应该是struct mystruct&record
不起作用,不是一个非常有用的描述你遇到什么问题。请告诉我们您得到的是什么输出。当我尝试这个引用时,错误有点奇怪,但就是这样:C没有传递引用,所有东西都是传递值。但funcrecord已将记录数组作为指针传递。也就是说,它已经被引用了,因为您似乎希望它不会复制整个结构数组。请在您的问题中包含您得到的特定错误。此外,您不需要在标题中添加标签。我们有相应的标签。请阅读有关数组、指针和隐式转换的内容。应该在任何一本好的C语言书中详细说明。对于初学者:不要像传递参考一样思考,即使你知道这不是实际发生的事情。顺便说一句,这正是我想要的,指针的第一个选项,我混淆了关于引用的内容,因为这些指针可以帮助你模拟同样的事情。谢谢这个问题被标记为c,所以没有参考文献。您只在C++中获得引用。C不支持引用。你没有指出问题代码中的错误。原始代码是正确的,没有错误。struct mystruct record[]作为函数参数的含义与struct mystruct*record完全相同。