我收到一条错误消息,我不知道如何解决

时间:2021-07-21 23:10:28

标签: c

我收到此错误消息:

error: incompatible types when assigning to type 'Nombre {aka struct <anonymous>}' from type 'int':
nombre[0] = 'A'+(rand()%26);

代码:

typedef struct{
  char nombre[9];
}Nombre;

Nombre* crearNombre(){
    Nombre *nombre;
    nombre = (Nombre*)malloc(9* sizeof(char));
    nombre[0] = 'A'+(rand()%26);
    for (int i=1; i<9; ++i){
        if(i == 9){
            nombre[i] = '\0';
        }
        else nombre[i] = 'a'+(rand()%26);
    }
    return nombre;
}

这是什么意思,我该如何解决?

1 个答案:

答案 0 :(得分:1)

nombre 是指向结构 Nombre 的指针,所以 nombre[0] 是结构,而不是整数。

您应该分配正确的大小并引用成员 nombre 来访问元素。

另请注意,malloc() 族的转换结果为 considered as a bad practice

#include <stdlib.h>

typedef struct{
  char nombre[9];
}Nombre;

Nombre* crearNombre(){
    Nombre *nombre;
    nombre = malloc(sizeof(*nombre));
    if (nombre == NULL) return NULL;
    nombre->nombre[0] = 'A'+(rand()%26);
    for (int i=1; i<9; ++i){
        nombre->nombre[i] = 'a'+(rand()%26);
    }
    return nombre;
}

还有一点:我删除了 if(i == 9) 语句,因为在循环条件 i 下,9 永远不会是 i < 9