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.
Thanks for your help everyone. It was actually a memory issue elsewhere. The above code is correct.