2011-02-15 134 views
0

如果这是一个非常简单的问题,但我真的生锈在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()函数我没有在改变的自由,但我可以改变我的参数传递给它。

+1

`records [count] = cur-> rec`是对的,但是我没有通过检查`&record [1]来得到你想要的结果。你会想要在结构内部的东西,记录[1] .some_member – nos 2011-02-15 09:14:17

+0

@nos是现货......`&记录[1]`只是要求一个指向第一条记录的指针......它永远不可能是“结构的*值*” – 2011-02-15 09:18:57

回答

0

感谢您的帮助大家。这实际上是其他地方的记忆问题。上面的代码是正确的。

0
*(cur->rec) 

根据您发布的样本,这应该不起作用。

复制的记录结构的正确方法是:

records[count] = cur->rec; 

如果你想有一个指针链表的实际结构,你需要有一个指针数组来记录,而非目前的记录数组。在这种情况下,你分配:

records[count] = &(cur->rec); 
0

记录[计] = CUR-> REC是正确的,但是你错过CUR = CUR->未来。记录[1]是第二条记录,而&记录[1]是它的地址。

相关问题