I'm trying to assign the values of a struct to a map but the following error message appears after compiling:
error: incompatible types when assigning to type ‘char[25]’ from type ‘char *’
in
map[i].n=m.n
My struct is defined this way:
struct m1{
int c;
char n[25];
int q_m;
int q;};
Part of my code:
struct m1 m;
struct m1 *map = 0;
scanf("%d",&m.c);
scanf("%s",&m.n);
scanf("%d",&m.q_m);
scanf("%d",&m.q);
map[i].c=m.c;
map[i].n=m.n;
map[i].q_m=m.q_m;
map[i].q=m.q;
It seems like what you most likely want to do (besides allocating memory for the struct) is copying the contents of the array pointed to by
n
, instead of only copying the actual pointer.map
is a pointer and you should be allocating memory to it before writing something to it.Then you can have
After this fix string copy
You copy all of the structure members. The simplest way to do that is:
Looks like you are trying to assign directly m.n value to the array. Please see below detail Example :
In the above code snippet I am trying to assign "XYZ" to the array which is the member of struct db. It through the similar Error because of ptr->db_name = "xyz";
st_dyna_mem.c:14: error: incompatible types when assigning to type ‘char[10]’ from type ‘char *’
Fix : For Fixing this type of issue you Can use strcpy() or memcpy(). EX:
Output: db_num:10 db_name:xyz
First you need to allocate memory for
map
.and use
strcpy
to copym.n
tomap->n
.Array variables cannot be an lvalue to the assignment operator, that is they cannot be assigned anything.
To copy an array, copy element by element or use a "low-level" function like
memcpy()
to copy a specific amount of memory at once: