简体   繁体   中英

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

I am sorry if this is a really simple question but I am really rusty in C and googling hasn't helped so far. I have a C function that takes in an array of structs and an integer:

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

}

and also a linked list where each node has a struct:

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

and struct record is:

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

inside foo(struct record , int ) I am iterating through the linked list and assigning the first "n" struct records into the array like:

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++;
    }
}

I tried doing: records[count] = cur->rec

which compiles but when I do the following:

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.

but when I pass &records[0] to another function like:

checkrecord(&record[0]);

where checkrecord is declared:

checkrecord(const struct record *r)

inside that function, r->type and r->value.intval both return 0 instead of the correct value.

I'm pretty sure I'm storing the struct record into the array correctly, but I'm not sure what else I'm doing wrong.

I don't mean to sound stubborn but the issue is that the checkrecord() function I am not at liberty to change but I can change how I pass the parameters to it.

*(cur->rec)

This should not work given the sample you posted.

The correct way to copy the record struct is:

records[count] = cur->rec;

If you want a pointer to the actual struct in the linked list, you need to have an array of pointers to record, instead of your current array of records. In that case, you assign with:

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

records[count] = cur->rec is correct, but you're missing cur = cur->next. And record[1] is the second record, and &record[1] is its address.

Thanks for your help everyone. It was actually a memory issue elsewhere. The above code is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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