Error: incompatible types when assigning to type ‘

2020-07-30 01:00发布

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;

标签: c
7条回答
Rolldiameter
2楼-- · 2020-07-30 01:35

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.

strcpy(map[i].n, m.n);
查看更多
We Are One
3楼-- · 2020-07-30 01:40
struct m1 *map;

map is a pointer and you should be allocating memory to it before writing something to it.

map = malloc(sizeof(struct m1) * n);

Then you can have

map[i]

After this fix string copy

strcpy(map[i].n,m.n);
查看更多
家丑人穷心不美
4楼-- · 2020-07-30 01:42

You copy all of the structure members. The simplest way to do that is:

map[i]=m;
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-07-30 01:43

Looks like you are trying to assign directly m.n value to the array. Please see below detail Example :

#include<stdio.h>
#include<stdlib.h>

struct db{
    int db_num;
    char db_name[10];
};

int main()
{
    struct db *ptr;
    ptr = (struct db*)malloc(sizeof(struct db));
    ptr->db_num = 10;
    ptr->db_name = "xyz";
    printf("Input data Base:\n");
    printf("db_num:%d db_name:%s",ptr->db_num,(char*)ptr->db_name);
    return 0;
}

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:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct db{
    int db_num;
    char db_name[10];
};

int main()
{
    struct db *ptr;
    ptr = (struct db*)malloc(sizeof(struct db));
    ptr->db_num = 10;
    strcpy(ptr->db_name,"xyz");
    printf("Input data Base:\n");
    printf("db_num:%d db_name:%s",ptr->db_num,(char*)ptr->db_name);
    return 0;
}

Output: db_num:10 db_name:xyz

查看更多
祖国的老花朵
6楼-- · 2020-07-30 01:50

First you need to allocate memory for map.

struct m1 *map = malloc(sizeof(struct m1)); 

and use strcpyto copy m.n to map->n.

查看更多
可以哭但决不认输i
7楼-- · 2020-07-30 01:58

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:

memcpy(map[i].n, m.n, sizeof map[i].n);
查看更多
登录 后发表回答