Pushing a one-dimensional array to a 2-dimensional array in C

I am working on a queue data structure. Structure:

struct queue
{
 char array[MAX_LENGTH][8];
 int back;
};

It is designed to store a list of MAX_LENGTH strings with a length of 7 characters. I want to push a 1D array of 8 characters (well, 7 characters and \ 0, like the array in the structure).

I have this code:

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

I think this might work, but apparently not. In the cl compiler (.net C / C ++) I get the following error:

2.c (29): error C2106: '=': the left operand must be l-value

gcc returns a similar error on the same line (but I forgot and don't have access to gcc at the moment).

I am new to structures and pointers, so maybe something is very obvious that I am not doing. Appreciate any help :)

+3
4

q->array , . "" , , , ( q- > ). - :

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'; 
}

strcpy:

void push (struct queue *q, char s[]){
  strcpy(q->array[q->back], s);
}
+2

:

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

C =, - strcpy/memcpy .

+5

, strcpy C, strncat :

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);
}

, , s , ( ), memcpy :

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

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

-1
source

Source: https://habr.com/ru/post/1735055/


All Articles