Problem with strcpy

Asked

Viewed 226 times

-2

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

#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

I mean, the function is concatenating everything and obviously I don’t want that. Why is this function doing this if I didn’t cross the boundary of the space assigned to each field? And what should be done for each field to have its respective value?

1 answer

1


In C the strings need to have a binary zero at the end. So, their structure needs to reserve space for this binary zero. Therefore its structure must be declared so:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.