Program in c presenting output, strange different from the value of variables

Asked

Viewed 536 times

0

I’m having a problem running a program on and c that when I compile it and run it shows me a value that is not set in my variable I’m thinking it’s some bug with the ide or something related to the buffer I’ll leave a screenshot for you to see

the code:

struct c erro printf variavel

the exit:

saida extranha codigo c

1 answer

1


This error occurs because, you want to use a string(text) and only used a char(character). In the C language a string is represented by a string ending with a null character ' 0'. But you put only as char nick. The correct would be for example char nick[100];

When declaring char the compiler will allocate only 1byte of memory capable of storing a character.

char ao inves de string

However after placing this char[100] you will receive another error, check out:

inserir a descrição da imagem aqui

That is, it is not possible to assign a string field of a struct to a string constant "Assanges". To work you must use the function of (string copy) or strcpy(destination, origin). So put: strcpy(user.nick, "Assanges"); and it will work!

Remember to make string include. h

Check out:

inserir a descrição da imagem aqui

See below the correct code

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

struct User{
 char nick[100];
 int id;
}user;
int main(){
   strcpy(user.nick, "Assanges");
   user.id = 45474;
   printf("\nNick:%s\nId:%d \n", user.nick, user.id);

return 0;
}

Now when performing it will work!

inserir a descrição da imagem aqui

  • 3

    Cool a well explained answer, the only caveat is the use of images instead of text. It would be better to copy and paste the codes (just mark with the mouse and click the button { } Format bar, or press control-k to format as code. In text any user can copy and test the solution without having to rewrite everything. In addition, images generate a serious problem with accessibility and reading on small devices.

  • Thanks for the feedback! I liked it! I will do it in future answers! Hug

Browser other questions tagged

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