I am working on a queue data structure. The structure is:
struct queue
{
char array[MAX_LENGTH][8];
int back;
};
It is designed to store a list of MAX_LENGTH strings that are 7 chars long. I wish to push a 1D array of 8 chars (well, 7 chars and \0, just like the array in the struct).
I have this push code:
void push (struct queue *q, char s[]){
q->array[q->back] = s;
}
Which I figure might work, but apparently does not. In cl (.net's C/C++) compiler, I get the following error:
2.c(29) : error C2106: '=' : left operand must be l-value
gcc returns a similar error, on the same line (but I forget, and don't have access to gcc at the moment).
I'm fairly new to structs, and pointers so there's probably something very obvious I'm not doing. Appreciate any help :)
Change it to:
void push (struct queue *q, char s[])
{
strcpy(q->array[q->back], s);
}
You can assign structs in C using = but you can't assign arrays - you have to use strcpy/memcpy for things like this.
You have to treat q->array just as you would any other array. You can't just "push" it, you have to pass the location you want to put it in then copy each character (or use q->back as your location). Something like this perhaps:
void push (struct queue *q, char s[]){
int i;
for ( i = 0; s[i]; ++i )
q->array[q->back][i] = s[i];
q->array[q->back][i] = '\0';
}
Or use strcpy:
void push (struct queue *q, char s[]){
strcpy(q->array[q->back], s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With