2016-09-18 35 views
-2

我试图发送一个结构数组作为参考,但由于某种原因,我不能得到它的工作,因为价值是能够通过,但并不作为参考(&)通行证结构阵列的功能使用指针

这是我的代码:

#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(&记录),并改变FUNC功能参数为“结构MYSTRUCT *记录[]”这是去上班......但是它没有。

请任何帮助。

+0

“不工作”,是不是你遇到什么问题的一个非常有用的描述。请告诉我们你得到的输出。 – kaylum

+0

当我尝试引用这个错误时有点奇怪,但这是它: – Marco

+2

C没有引用传递,所有东西都是按值传递的。但'func(record)'已经传递了'record'数组作为指针。也就是说,它已经通过“引用”,就像你想要的一样(它不会复制整个结构数组)。 – kaylum

回答

-2

我认为你已经把你的指针和引用概念混淆了。

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 record[]应该已经struct mystruct & record
+0

哦,是的,这正是我正在寻找的,指针的第一个选项,我混淆了关于引用的东西,因为这些指针可以帮助您模拟相同的事物。谢谢 – Marco

+3

这个问题被标记为'c',所以没有任何引用。你只能在'C++'中获得引用。 –

+2

C不支持引用。而且你没有指出问题代码中的错误。 – Olaf