When trying to do this: g->v i=aux;
, I get:
ERROR: lvalue required as left operand of assignment"
The g->v
is a pointer to a dynamically allocated array of children.
Even after allocating space for the array, the compiler doesn't like it when I increment the pointer.
int n=5
struct group
{
int n,x,y,exp,r;
struct group *v;
};
void init_group(struct group *g)
{
g->v=malloc(sizeof(struct group*)*(n));//an array of n elements
for(int i=0; i<n; i )
{
struct group *aux;
g->v i=aux; **// HERE IS THE ERROR**
}
}
What am I doing wrong and what alternative can I use?
CodePudding user response:
First, your v
member is a struct group*
, which will allow it to hold an array of structures; but you are allocating it (and attempting to assign it) as though it were an array of pointers to structures.
So – if the malloc
call is doing what you actually want it to (i.e. creating an array of n
pointers) – then that member should be declared as a pointer-to-pointer: struct group** v;
.
Second, when accessing array elements, avoid confusion by not using pointer arithmetic: that's what the []
operator is for; a simple g->v[i] = aux;
will do the job for you.
Here's a modified/working version of your code:
#include <stdio.h>
#include <stdlib.h>
int n = 5;
struct group
{
int n, x, y, exp, r;
struct group** v; // Double pointer to hold an array of POINTERS
};
void init_group(struct group* g)
{
g->v = malloc(sizeof(struct group*) * (n));//an array of n elements
for (int i = 0; i < n; i )
{
struct group* aux = NULL; // Actually give a value?
g->v[i] = aux; // Use the array's [] operator
}
}
If you really insist on using pointer arithmetic, rather than the []
operator, then (after correcting the member type to a pointer-to-pointer), the syntax is as follows:
*(g->v i) = aux;