Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

How to write a good struct?


ghost's Avatar
0 0
struct pack {
   ex_1;
   ex_2;
}

int main() {
   pack.ex_1.num = 5;
   pack.ex_2.num = 6;
}

Is that the right way to write a structure in C++, or am I doing it wrong…?


ghost's Avatar
0 0

Hmm…you need to create an instance of the struct before you assign variables to it.

struct pack {
  ex_1;
  ex_2;
};

int main() {
  struct pack exampleStruct; //creates an instance of "pack"
                                        //called "exampleStruct"
  exampleStruct.ex_1 = 5; //initialize member ex_1
  exampleStruct.ex_2 = 6; //initialize member ex_2
}

Oh and you need a semicolon after the } when you define a structure.

If it helps, think of structures as another variable type, like int or char. you can use a struct however many times you want. you create an instance of a structure just like you would an integer, like this:

//initialize variables in struct here, or as an array: 
//[structname] = {var, var, ...};```

Hope that helps. That's what I've learned from C at least, I assume it applies to C++ as well.

ghost's Avatar
0 0

What about a struct inside the actual structure itself..?

struct package {
   struct ques ex_1;
   struct ans ans_2;
}

Then call the whole structure in the main() ?


ghost's Avatar
0 0

This way :

{
    int val1;
    int val2;
};

struct pack1 pack1;

struct pack
{
    pack1 val1;
    pack1 val2;
};

struct pack pack;```

ghost's Avatar
0 0
#include <stdio.h>
#include <stdlib.h>

typedef struct pack
{
	int val1, 
		val2;
}PACK;

typedef struct pack_1
{
	PACK pack_val1;
	PACK pack_val2;
}PACK_1, *LPPACK_1;

int main(int argc, char **argv)
{
	PACK_1 *myPackOne = (LPPACK_1)malloc(sizeof(PACK_1));
	myPackOne->pack_val1.val1 = 10;
	myPackOne->pack_val2.val1 = 15;
	myPackOne->pack_val1.val2 = 7;
	myPackOne->pack_val2.val2 = 24;
	printf("%d\n", myPackOne->pack_val1.val1);
	printf("%d\n", myPackOne->pack_val2.val1);
	printf("%d\n", myPackOne->pack_val1.val2);
	printf("%d\n", myPackOne->pack_val2.val2);

	return 0;
}