I'm having a little problem with a function which receives as a parameter an array of structures, the problem occurs when trying to access array elements with operator ->
#include <stdio.h>
typedef struct{
int order;
}record;
void entry(record*reg, size_t num_regs);
int main(void){
record reg[10];
entry(reg, sizeof reg / sizeof reg[0]);
return 0;
}
void entry(record*reg, size_t num_regs){
size_t i;
for (i = 0; i < num_regs; i++){
reg[i]->order = i;
printf("\n order = %d", reg[i]->order);
}
}
throws this error if you try to compile
*error #2140: Type error in argument 1 to 'ingreso'; expected 'registro * *' but found 'registro *'.*
because it throws this error and how to fix it?
When you use [ ] for pointer you already have a data, so use . instead of ->
reg[i].order = i;
and the same for printf argument.
I tried your code like this and whole of the array printed exactly true:
for (i = 0; i < num_regs; i++){
reg->order = i;
printf("\n order = %d", reg->order);
}
You need to understand the difference between the ->
and .
operators when accessing data inside of a struct
.
sa
is just for when s
is a struct
and a
is a member of s
sp->a
is really just a shorthand for (*sp).a
This is used when sp
is a pointer-to- struct
, and we want to dereference that pointer and access the struct
's data all in one step. As VolAnd said , you are using reg[i]->order
but you should really be using reg[i].order
.
If it's still unclear...
With your entry()
function, you are passing in an array of 10 record structs
called reg
. You do this by passing a pointer to the array's base address, so the function accepts a pointer of type record*
.
The elements of the array are structs
, not struct
pointers , so you access them with reg[i].order
, not reg[i]->order
.
Here you are passing address of array and storing / collecting is in pointer. And as the pointer is pointing to array, if you use -> operator to access the structure element it will treat array as pointer and throws error as "error: invalid type argument of â->â (have ârecordâ)".
So you have to use (.) operator instade of (->) operator.
for (i = 0; i < num_regs; i++)
{
reg[i].order = i;
printf("\n order = %d", reg[i].order);
}
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.