I am changing an exercise that creates a linked list of integers to a linked list of strings. But I have an error in the method push()
, which I have adapted from the original exercise that does work.
I have a linked list defined like this:
typedef struct nombreLista {
char nombre[50];
struct nombreLista* siguiente;
} Nombre;
I create the variables I need, for the list and the index of the list:
Nombre *pNombres;
int size;
Next I initialize the list:
void init() {
pNombres = NULL;
size = 0;
}
Now, I have this function to put an element in the list, it receives a name as a parameter and tries to insert this data in the list, returning 0 on success and -1 on failure.
int push(char dato[50]) {
Nombre* nodo = (Nombre *)malloc(sizeof(Nombre)); // No sé que hace esta línea
if (nodo != NULL) {
nodo->nombre = dato;
nodo->siguiente = pNombres;
pNombres = nodo;
size++;
return 0;
} else {
printf("No se pudo agregar el nombre");
return -1;
}
}
I get a compile error:
error C2106: '=': el operando izquierdo debe ser valor L
The IDE displays the error on the line nodo->nombre = dato;
with the legend la expresión debe ser un valor L modificable
. The compiler is that it comes with Visual Studio 2019.
What does the error mean and how can I fix it? Additionally, what does the line do Nombre* nodo = (Nombre *)malloc(sizeof(Nombre));
?
The error means that you cannot assign any element to the implicit pointer
nombre
.It's like if you did this:
It will give a compilation error, it is only valid to assign something (it must be a literal string) to
nombre
when declaring it.For example:
If the identifier
nombre
were a member of a structure, it would give the same error:It will also give a compile error because we can't assign anything to the member
nombre
after the declaration ofA
. Instead, if I do this:There would not be a compilation error, because the string "Dave" is being assigned in
nombre
but in the declaration ofa
, therefore, there would be no problem there.Solution:
You can make use of the strcpy function to be able to copy the content of one type array to
char
another.C code:
Another solution to be able to save the function
strcpy
is changing the declaration ofnombre
.That is, if you had defined the structure in this way:
You can change it to:
There it would not give any compilation error.
Why? Because the variable
nombre
is now modifiable and this is because it was declared as an explicit pointer.This is like if you did this:
What you receive
n
is the base address of the arraynombre
(that is, of the first element).What the malloc function does is allocate dynamic memory at run time (in this case, what it creates in memory is a data buffer). In which, it will return the first memory address of the node and save it in the variable
nodo
.