Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can´t print a String from a structure in C

typedef struct listaDocente nodoDocente;
struct listaDocente{            //teacherList
    char Rut[12];               //ID
    char Nombre[50];            //Name
    char Correo[70];            //Email
    char Cod_Curso[6];          //Grade_Code
    char Asignatura[15];        //Grade_Name
    nodoDocente *siguiente;     //Next (Node)
};

int main(){
    nodoDocente *D = ((nodoDocente * )malloc(sizeof(nodoDocente)));
    strcpy(D->Nombre, "Charlie");
    strcpy(D->Rut, "18123456");
    strcpy(D->Asignatura, "EDD");
    strcpy(D->Cod_Curso, "INS123");
    strcpy(D->Correo, "[email protected]");
    printf("%s\n", D->Nombre);
    printf("%s\n", D->Rut);
    printf("%s\n", D->Asignatura);
    printf("%s\n", D->Cod_Curso);
    printf("%s\n", D->Correo);

    return 0;
}

First, sorry if some words are in spanish. Im trying to print these values but i'm gettin a blank space.

Charlie
18123456

INS123
[email protected]

Where it should be printing out EDD, like this.

Charlie
18123456
EDD
INS123
[email protected]
like image 338
Calu Avatar asked Dec 08 '22 22:12

Calu


1 Answers

You have declared :

char Cod_Curso[6];

and filled it with :

strcpy(D->Cod_Curso, "INS123");

But INS123 is followed by the terminating character for strings \0. So instead of 6 characters as you might think, the string INS123 actually occupies 7 characters. As a result, you cannot expect the statement :

printf("%s\n", D->Asignatura);

to work properly as you invoke undefined-behavior with the previous line.

Solution : Declare Cod_Curso with size 7 (or more), like this :

char Cod_Curso[7];

Also, take a look at this link on why not to cast the result of malloc.

like image 183
Marievi Avatar answered Dec 30 '22 03:12

Marievi