-6

I am getting this error message:

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

The code:

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

What does it mean and how can I fix it?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nico
  • 1
  • 2
  • What are you hoping `nombre[0]` refers to? The `nombre` pointer in this context represents a `Nombre` struct, not the `nombre[9]` character array within one of these structs. – jarmod Jul 21 '21 at 23:13
  • 4
    @Nico Welcome to SO! Please choose a title that describes your technical problem that others might search for. – ggorlen Jul 21 '21 at 23:18

1 Answers1

1

nombre is a pointer to the structure Nombre, so nombre[0] is the structure, not an integer.

You should allocate correct size and refer the member nombre to access the elements.

Also note that casting results of malloc() family is 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;
}

One more point: I removed the if(i == 9) statement because i will never be 9 under the loop condition i < 9.

Oka
  • 23,367
  • 6
  • 42
  • 53
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Also, use more detailed naming, You might not have confused yourself if you had used `NombreStruct *nombre_struct;` then you might see that you needed `nombre_struct->nombre` – Dave S Jul 21 '21 at 23:16