How to print string struct in c?

Asked

Viewed 95 times

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 name strcpy(cp.nome, "joa") or add one more space in name char nome[5], your program should work correctly.

  • @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.

  • 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; ;}

  • I’m compiling the code I pasted up and it’s working.

  • @Thank you very much! You saved my life. Now I have managed to build the code I need for the university. vlw msm

1 answer

0


I suggest you don’t set how many characters the string has, because when you can’t assign the string that way, just by strcpy, aleḿ of you not leaving space for the empty character ' 0', and the advantage of the string is exactly not having to leave a fixed size, look how I left:

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

  struct DATA {
    char *nome;
    char *sobrenome;
    char *apelido;
  };

  int main()
  {
    struct DATA cp;

    cp.nome = "joaao";
    cp.sobrenome = "zuadao";
    cp.apelido = "furao";

    printf("%s / %s / %s\n", cp.nome, cp.sobrenome, cp.apelido);

    return 0;
  }
  • 1

    Thank you so much for sharing your solution. It helped me learn a lot! ^^

Browser other questions tagged

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