Problem with strcpy [duplicate]

-2

I'm trying to fill in the fields of a struct with strcpy but I'm not getting the expected value, such as:

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

struct Aluno {
    char tipo;
    char matricula[8];
    char idade[2];
    char nome[40];
};

int main( )
{

    struct Aluno m;

    m.tipo = '5';
    strcpy(m.matricula, "20101122");
    strcpy(m.idade, "30");
    strcpy(m.nome, "Jack Revoltado");

    printf(" Tipo do aluno = %c\n",m.tipo);
    printf(" matricula %s\n",m.matricula);
    printf(" tamanho %s\n",m.idade);
    printf(" nome %s\n",m.nome);

    return 0;
}

Whose exit is:

Tipo do aluno = 5
 matricula 2010112230Jack Revoltado
 tamanho 30Jack Revoltado
 nome Jack Revoltado

That is, the function is concatenating everything and obviously I do not want it. Why is this function doing this if I have not moved beyond the boundary of the space allocated to each field? And what should be done so that each field has its value?

    
asked by anonymous 28.10.2018 / 20:59

1 answer

1

In C the strings need to have a binary zero at the end. So, their structure needs to allocate space for that binary zero. So your structure should be declared like this:

struct Aluno
{
  char tipo;
  char matricula[9]; // <---
  char idade[3];     // <---
  char nome[41];     // <---
};
    
28.10.2018 / 21:28