Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing a 1-D array onto a 2-D array in C

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

like image 246
Martin Pugh Avatar asked May 14 '26 01:05

Martin Pugh


2 Answers

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.

like image 112
Paul R Avatar answered May 15 '26 19:05

Paul R


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);
}
like image 35
IVlad Avatar answered May 15 '26 19:05

IVlad