繁体   English   中英

如何获取结构内部的结构并将其分配给结构数组

[英]how to get a struct that inside of a struct and assign it to an array of structs

很抱歉,如果这是一个非常简单的问题,但我对C感到非常生疏,到目前为止,Google搜寻还没有帮助。 我有一个C函数,它接受一个结构数组和一个整数:

int foo(struct record *records, int n)
{

}

以及每个节点都有一个结构的链表:

struct rnode
{
    struct record rec;
    struct rnode *next;
}

和结构记录是:

struct record
{
    enum recordtype type;
    union recordvalue
    {
        int intval;
        char strval[19];
    } value;
};

在foo(struct record ,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++;
    }
}

我试着做:records [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.

但是当我将&records [0]传递给另一个函数时,例如:

checkrecord(&record[0]);

声明checkrecord的位置:

checkrecord(const struct record *r)

在该函数内部,r-> type和r-> value.intval都返回0而不是正确的值。

我很确定我将struct记录正确地存储到了数组中,但是我不确定我在做什么错。

我并不是说听起来很固执,但问题是我没有随意更改checkrecord()函数的权限,但可以更改将参数传递给它的方式。

*(cur->rec)

给定您发布的示例,此方法不起作用。

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

records[count] = cur->rec;

如果要在链接列表中指向实际结构的指针,则需要有一个要记录的指针数组,而不是当前的记录数组。 在这种情况下,您可以分配:

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

records [count] = cur-> rec是正确的,但是您缺少cur = cur-> next。 而record [1]是第二个记录,&record [1]是它的地址。

谢谢大家的帮助。 这实际上是其他地方的内存问题。 上面的代码是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM