0
When time print strings of a struct the program compiles and returns 0 but the values of the strings are not expected. Follow the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct DATA{
char nome[4];
char sobrenome[6];
char apelido[5];
};
int main(){
struct DATA cp;
cp.nome[4] = "joao";
cp.sobrenome[6] = "zuadao";
cp.apelido[5] = "furao";
printf("%s / %s / %s\n", cp.nome, cp.sobrenome, cp.apelido);
return 0;
}
The value returned in the console is: @ / D / IÇ
Can someone help me? Thanks.
The problem is that vc is not leaving space in the empty character pro array
'\0'
. If you copy only the first 3 characters for namestrcpy(cp.nome, "joa")
or add one more space in namechar nome[5]
, your program should work correctly.– aviana
@Aviana. Thanks for the help. I did what you said. But the return is still not the string values. This problem only happens with struct.
– vitor
int main() { struct DATA cp; strcpy(cp.first name, "Joa"); strcpy(cp.last name, "zuada"); strcpy(cp.last name, "fura"); printf("%s / %s / %s n", cp.first name, cp.last name, cp.last name); Return0; ;}
– aviana
I’m compiling the code I pasted up and it’s working.
– aviana
@Thank you very much! You saved my life. Now I have managed to build the code I need for the university. vlw msm
– vitor