Search code examples
cstructstrcmp

Why when i'm using strcpy in struct are copying everything to the same variable - c language


look guys, i have the code above

#include <stdio.h>
#include <string.h>
#define MAX 5
typedef struct Estudante{
    char nome[MAX];
    char apelido[MAX];
    char residencia[MAX];
    int telefone;
}TEstudante;
int equalEnty(TEstudante *estudante_1,TEstudante *estudante_2);
int comesFirst(TEstudante *estudante_1,TEstudante *estudante_2);
int main(){

    TEstudante estudantes[2];
    strcpy((estudantes[0]).nome,"Angelo");
    strcpy(estudantes[0].apelido,"Pelon");
    strcpy(estudantes[0].residencia,"3B");
    estudantes[0].telefone = 33813001;

    strcpy(estudantes[1].nome,"Angelo");
    strcpy(estudantes[1].apelido,"Pelon");
    strcpy(estudantes[1].residencia,"3C");
    estudantes[1].telefone = 33813001;

    printf("%d",comesFirst(&(estudantes[0]),&estudantes[1]));

    return 0;
}

int equalEnty(TEstudante *estudante_1,TEstudante *estudante_2){

    if(strcmp((*estudante_1).nome,(*estudante_2).nome)!=0)
        return 0;
    if(strcmp((*estudante_1).apelido,(*estudante_2).apelido)!=0)
        return 0;
    if(strcmp((*estudante_1).residencia,(*estudante_2).residencia)!=0)
        return 0;
    if((*estudante_1).telefone != (*estudante_2).telefone)
        return 0;
    return 1;
}

int comesFirst(TEstudante *estudante_1,TEstudante *estudante_2){
    printf("%s %s",(*estudante_1).nome,(*estudante_2).nome);
    return strcmp((*estudante_1).nome,(*estudante_2).nome);
}

Then when i printf the content insite the comesFirst function its are showing something like that:

AngeloPelon3B AngeloPelon3C-1

Why if i added separetly the strins to the structs areas !?


Solution

  • You need 7 characters in an array to copy "Angelo" to it, not five. The length of the string is 6 and you need an extra character for the terminating null character.

    You are writing over memory of other fields when you execute:

    strcpy((estudantes[0]).nome,"Angelo");
    

    Define MAX go be 1 more than the maximum length of the strings you are going to copy into nome, apelido, and residencia.