manipulation of some struct

Asked

Viewed 118 times

0

I have a struct, how do I predefine data in this struct? example define life of struct 100?

I’ve tried to dataplyer.vida = 100;

struct dataplayer
{
    int vida;
    int armadura;
    int arma;
    int level;
};
  • What is the problem you are having ? The modification has no effect ? It gives error ? If yes which ? It is not very clear to us what is happening.

2 answers

1

If I understand correctly, you want the life field to have a default value of 100 when the struct is instantiated. If you are coding in C it is unfortunately not possible, as you cannot assign values to unspecified structures. But if you’re coding in C++, where structs work in exactly the same way as classes (but with differentiated standard scopes) you can solve this problem with a constructor inside the struct:

#include <iostream>

using namespace std;

struct dataplayer
{
    int vida;
    int armadura;
    int arma;
    int level;

    dataplayer() {
       this->vida = 100;
    }
};

int main() {

    struct dataplayer player; /*No momento da instancia o construtor sera chamado e
                                a vida sera alterada para 100 */
    return 0;
}
  • That’s right! That’s what I wanted to know. + 1

0


The problem must be in another area of the code, apparently, you seem to be correctly defining the attribute. So I suppose your problem is something else, but to answer the question, just use the "." (period) to access the element you need and the assignment operator "=" to assign the value.

Logically, you need to create a "variable" to perform the assignment of the real value of a player in memory, in my case P1.

Follow an example:

#include <iostream>

using namespace std;

struct dataplayer { int vida; int armadura; int arma; int level; };

int main()
{
    cout<<"definindo a vida \n";

    //seu player
    dataplayer p1;

    p1.vida = 100;

    cout << p1.vida;

    return 0;
}

You can test this code here:

https://www.onlinegdb.com/online_c++_Compiler

Note: It is also not clear to me, and I am sleepy, if you code in c or c++, I recommend that you choose a.

  • Solved friend! Vlw

  • ok mark the answer on the question, t+

Browser other questions tagged

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