HI PLEASE DESCRIBE THESE IN BEGINNER TERMS IN C++, GIVE SYNTAX WHEN NEEDED AND P
ID: 3574993 • Letter: H
Question
HI PLEASE DESCRIBE THESE IN BEGINNER TERMS IN C++, GIVE SYNTAX WHEN NEEDED AND PLEASE EXPLAIN THOUROUGHLY FOR SOMETHING I CAN PUT ON CHEAT SHEET!!
Structures IN C++
•Know how to define one
•Know how to create an instance of one
•Know how to reference fields within a structure using a reference argument
•Know how to initialize one when declaring an instance of a structure and when an instance of a structure already exists
•Know what sizeof() is used for
•Know how to create an array of struct
•Know how to access individual structs in an array of struct as well as data members for individual structs
Explanation / Answer
•Know how to define one
A structure is a user defined data type in C/C++.
A structure creates a data type that can be used to group items of possibly different types into a single type.
'struct' keyword is used to create a structure.
Ex:
struct Person{
char name[50];
int id;
double salary
};
•Know how to create an instance of one
A structure variable can either be declared/created with structure declaration or as a separate declaration like basic types.
// A variable declaration with structure declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'
// A variable declaration like basic data types
struct Point
{
int x, y;
};
int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
•Know how to reference fields within a structure using a reference argument
Structure members are accessed using dot (.) operator.
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
// Accesing/referencing members of point p1
p1.x = 20;
cout<<p1.x<<p1.y;
return 0;
}
•Know how to initialize one when declaring an instance of a structure and when an instance of a structure already exists
struct Point
{
int x ;
int y ;
};
initialize one when declaring an instance:
struct Point p1 = {0, 1};
initialize one when instance of a structure already exists
struct Point p1;
p1.x = 0;
p1.y = 1;
•Know what sizeof() is used for
sizeof() is used to calculate the size taken by structure
•Know how to create an array of struct
Like other primitive data types, we can create an array of structures.
struct Point
{
int x, y;
};
// Create an array of structures
struct Point arr[10];
// Access first array members
arr[0].x = 10;
arr[0].y = 20;
•Know how to access individual structs in an array of struct as well as data members for individual structs
We can access inidividula structs in an array using index(index starts with 0)
// Create an array of structures
struct Point arr[10];
arr[3].x = 10;
arr[3].y = 20;
// Access fourth array members
cout<<arr[3].x;
cout<<arr[3].y
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.