Declares a struct that stores the name and age of a person.

Declares a struct that stores the name and age of a person.

The Battle Louis Simpson

Afflluence Writng Service

Structure is a collection of factors of various information sorts under a solitary name. It is like a class in that, the two holds a collecion of information of various information sorts.

For instance: You need to store some data about a man: his/her name, citizenship number and compensation.

You can without much of a stretch create distinctive factors name, citNo, compensation to store these data independently.

In any case, later on, you would need to store data about numerous people. Presently, you’d have to create diverse factors for each data per individual: name1, citNo1, salary1, name2, citNo2, salary2

You can without much of a stretch envision how enormous and muddled the code would look. Likewise, since no connection between the factors (data) would exist, it will be an overwhelming assignment.

A superior approach will be to have a collection of all related data under a solitary name Person, and utilize it for each individual. Presently, the code looks much cleaner, coherent and efficient also.

This collection of all related data under a solitary name Person is a structure.

How to declare a structure in C++ programming?

The struct catchphrase characterizes a structure sort took after by an identifier (name of the structure).

At that point inside the curly braces, you can declare at least one individuals (declare factors inside curly braces) of that structure. For instance:

struct Person

{

char name[50];

int age;

coast compensation;

};

Here a structure individual is characterized which has three individuals: name, age and pay.

At the point when a structure is created, no memory is allocated.

The structure definition is just the outline for the creating of factors. You can envision it as a datatype. When you characterize a whole number as underneath:

int foo;

The int specifies that, variable foo can hold whole number component as it were. So also, structure definition just specifies that, what property a structure variable holds when it is characterized.

Note: Remember to end the declaration with a semicolon (;)

How to characterize a structure variable?

Once you declare a structure individual as above. You can characterize a structure variable as:

Individual bill;

Here, a structure variable bill is characterized which is of sort structure Person.

At the point when structure variable is characterized, at exactly that point the required memory is allocated by the compiler.

Considering you have either 32-bit or 64-bit framework, the memory of buoy is 4 bytes, memory of int is 4 bytes and memory of char is 1 byte.

Hence, 58 bytes of memory is allocated for structure variable bill.

How to access individuals from a structure?

The individuals from structure variable is accessed utilizing a dab (.) administrator.

Assume, you need to access time of structure variable bill and dole out it 50 to it. You can play out this undertaking by utilizing following code underneath:

bill.age = 50;

Illustration: C++ Structure

C++ Program to relegate information to individuals from a structure variable and show it.

#include

utilizing namespace sexually transmitted disease;

struct Person

{

char name[50];

int age;

coast pay;

};

int principle()

{

Individual p1;

cout > p1.age;

cout > p1.salary;

cout The Battle Louis Simpson

Affluuence Writng Service

A estrutura é uma coleção de fatores. É uma classe naquilo, os dois mantêm um relatório de vários tipos de informação.

Por exemplo: Você precisa obter alguns dados sobre um homem: seu nome, número de cidadania e compensação.

Você não pode criar um nome específico de fatores específicos, citNo, compensação para armazenar esses dados de forma independente

Em qualquer caso, você precisará armazenar dados sobre inúmeras pessoas Atualmente, você precisa ter fatores diferentes para cada dado por pessoa: nome1, citNo1, salário1, nome2, citNo2, salário2

Você pode muito de um estiramento imaginar o quão enorme e confuso o código irá olhar. Da mesma forma, uma vez que nenhuma conexão entre os fatores existirá, será uma tarefa irresistível.

Uma abordagem superior será uma coleção de todos os dados relacionados sob um nome solitário, e utilizá-lo para cada indivíduo Atualmente, o código parece muito mais limpo, coerente e eficiente também.

Esta coleção de todos os dados relacionados

Como declarar uma estrutura na programação C ++?

A sequência de captura de estrutura caracteriza uma estrutura classificada por um identificador (nome da estrutura).

Nesse ponto, dentro dos aparelhos de fraldas, você pode declarar pelo menos uma pessoa (declarar fatores dentro de chaves) dessa estrutura. Por exemplo:

pessoa estruturada

{

nome de caras [50];

idade normal;

compensação costeira;

};

Aqui está uma estrutura caracterizada por três pessoas: nome, idade e salário.

No momento em que uma estrutura é criada, nenhuma memória é alocada

A definição da estrutura é apenas o esboço para a criação de fatores Você pode visualizá-lo como um tipo de dados. Quando você caracteriza um número inteiro como abaixo:

int foo;

O int especifica que, a variável foo pode conter todo o componente do número, por assim dizer. Então também, o que é um déficit de propriedade?

Nota: Lembre-se de encerrar a declaração com um ponto-e-vírgula (;)

Como caracterizar uma variável de estrutura?

Uma vez que você declara uma estrutura individual como acima Você pode uma variável de caractere como:

Conta individual;

Aqui, uma variável de estrutura é a característica

No momento em que a variável da estrutura é caracterizada, nesse ponto

Considerando que você possui estrutura de 32 bits ou 64 bits, a memória da bóia é de 4 bytes, a memória do int é de 4 bytes ea memória do char é de 1 byte. (Declares)
Portanto, 58 bytes de memória são alocados para a conta de variável de estrutura.

Como acessar pessoas de uma estrutura?

As pessoas da variável de estrutura são acessadas usando um administrador dab (.).

Suponha que você precisa acessar o tempo da contabilidade variável da estrutura e distribuí-la 50. Você pode jogar este trabalho usando o seguinte código abaixo:

bill.age = 50;

Ilustração: Estrutura C ++

Programa C ++ para relegar informações para uma variável de estrutura e mostrá-la.(Declares)

#include

utilizando doenças sexualmente transmissíveis;

pessoa estruturada

{

nome de caras [50];

idade normal;

pagamento costeiro;

};

princípio int ()

{

Individual p1;

cout > p1.age;

cout > p1.salary;

cout

You may also like...

1 Response

  1. 2017

    […] Declares a struct that stores the name and age of a person. […]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

error: Content is protected !!