如果这是一个非常简单的问题,但我真的生锈在C和谷歌搜索没有帮助到目前为止,我很抱歉。我有一个C函数,它在结构的数组和一个整数:如何获得一个结构,在一个结构中,并将其分配给一个结构数组
int foo(struct record *records, int n)
{
}
并且还链接列表,其中每个节点具有结构:
struct rnode
{
struct record rec;
struct rnode *next;
}
和struct记录是:
struct record
{
enum recordtype type;
union recordvalue
{
int intval;
char strval[19];
} value;
};
foo(结构记录,int)我遍历链表并将第一个“n”结构记录分配到数组中,如:
int foo(struct record *records, int n)
{
int count = 0;
struct rnode *cur = recordlist;
while(cur != NULL)
{
records[count] = cur->rec; //Basically, how do I write this line?
printf("%d\n", records[count].type); //Both these print the correct values
printf("%d\n", records[count].value.intval); //Prints correct values
count++;
}
}
我试图做: 记录第[count] = CUR-> REC
其中编译但是当我执行以下操作:
struct record *records = malloc(sizeof(struct record)*n);
foo(records, n); //This should populate the array records but it isn't.
//If I print record[0].value.intval here I get 0.
但是当我通过&记录[0]到另一个功能,如:
checkrecord(&record[0]);
其中声明checkrecord:
checkrecord(const struct record *r)
里面的函数,r-> type和r-> value.intval都返回0而不是正确的值。
我很确定我正确地将结构记录存储到数组中,但我不知道我在做什么错了。
我并不是说固执,但问题是checkrecord()函数我没有在改变的自由,但我可以改变我的参数传递给它。
`records [count] = cur-> rec`是对的,但是我没有通过检查`&record [1]来得到你想要的结果。你会想要在结构内部的东西,记录[1] .some_member – nos 2011-02-15 09:14:17
@nos是现货......`&记录[1]`只是要求一个指向第一条记录的指针......它永远不可能是“结构的*值*” – 2011-02-15 09:18:57