Reputation: 21019
I have two arrays, each initialised as follows:
struct file_descriptor *list1 = (struct file_descriptor *)malloc(4096 * sizeof(struct file_descriptor));
struct file_descriptor *list2 = (struct file_descriptor *)malloc(4096 * sizeof(struct file_descriptor));
Each array is essentially a list of struct file_descriptor
pointers.
Now list1
already has a pointers in the array (that point to struct file_descriptor
's), and I need to have the same indices in list2
point to the same objects that list1
pointers point to. So if list1[2] = some_object
, I'm trying to point list2[2] = some_object
as well.
So:
int i;
for(i = 3; i < 4096; i++) {
struct file_descriptor *parent_fd = &list1[i]; // points to the struct that element at i points to in list1
list2[i] = parent_fd;
}
At line 2 in the loop, this throws a:
incompatible types when assigning to type ‘struct file_descriptor’ from type ‘struct file_descriptor *’
error.
Obviously, that's because list2[i]
is the actual struct file_descriptor
, and not the pointer in the list2
which points to that struct. Changing it to &list2[i] = parent_fd;
also throws an error because &list2[i]
is not an lvalue.
How would I dereference the pointer in the array at index i
, so that list2[i]
points to *list1[i]
Upvotes: 0
Views: 552
Reputation: 3663
list1
and list2
are of type struct file_descriptor **
not struct file_descriptor *
.
Further, don't declare a struct file_descriptor
pointer or variable inside a loop.
Anyways,if you want the pointers in list2
to point to the same structure variables as the respective pointers in list1
do,then it's fairly simple.You do it as:
for(i=0;i<=4096;i++)
list2[i]=list1[i];
Further, if you intend your arrays to be arrays of pointers
to the the structure variables, instead of arrays of structure variables, then you should use the following:
malloc(4096 * sizeof(struct file_descriptor*)); //note the second *
Edit Your line list2[i] = parent_fd;
shows type mismatch because you have declared list2
as of type struct file_descriptor*
and hence list2[i]
is of type struct file_descriptor
, while parent_fd
is of type struct file_descriptor*
.In simple words,the left side of the =
is a struct variable while the right side is a pointer to a struct variable. Like I said, you should declare list1
and list2
as type struct file_descriptor**
not struct file_descriptor*
.That should deal with the warning you encountered.
Upvotes: 1