views:

100

answers:

4

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 :)

+5  A: 

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.

Paul R
Maybe add some checking against buffer overflow?
Jonathan Leffler
+1  A: 

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);
}
IVlad
Oh thank you. strcopy helps greatly.
Martin Pugh
A: 

strncpy(q->array[q->back], s,MAX_LENGTH) could be better to avoid buffer overflow

luca
MAX_LENGTH is not the right constant here.
Paul R
you are right i mean 8
luca
With strncpy(), you have to ensure null termination; it doesn't. So you'd also need `q->array[q->back][7] = '\0';`. We can discuss whether the last parameter to strncpy() should be 8 (safe enough) or 7 (since you're about to overwrite the 8th place...).
Jonathan Leffler
A: 

If you want a bounds-checked strcpy using only the standard C library functions, then strncat is actually your best bet:

void push (struct queue *q, char s[])
{
    q->array[q->back][0] = 0;
    strncat(q->array[q->back], s, sizeof q->array[q->back] - 1);
}

On the other hand, if you know for certain that s always points to an array of the same size as the array in the struct (as your question states), then memcpy is the simplest solution:

void push (struct queue *q, char s[])
{
    memcpy(q->array[q->back], s, sizeof q->array[q->back]);
}
caf