Programar em C/Estruturas: diferenças entre revisões

[edição verificada][edição não verificada]
Conteúdo apagado Conteúdo adicionado
Abacaxi (discussão | contribs)
Sem resumo de edição
C++ não é C
Linha 286:
}
</pre>
 
== Estruturas aninhadas ==
 
A ideia é ter uma estrutura dentro de outra estrutura.
<pre>
#include <stdio.h>
struct Date //estrutura chamada de date
{
int month;
int day;
int year;
};
struct Person
{
string name;
int height;
Date bDay; //temos uma nova variável, mas notem a tipologia
};
void setValues(Person*);
void getValues(const Person*);
int main ()
{
Person p1;
setValues(&p1);
printf("Outputting person data\n");
printf("======================\n");
getValues(p1);
return 0;
}
void setValues(Person* pers)
{
printf("Enter person's name: ");
fgets(pers.name, 100, stdin);
printf("Enter height in inches: ");
scanf("%d", &pers.height);
printf("Enter month, day and year of birthday separated by spaces: ");
cin >> pers.bDay.month >> pers.bDay.day >> pers.bDay.year;
}
void getValues(const Person* pers)
{
cout << "Person's name: " << pers.name << endl;
cout << "Person's height in inches is: " << pers.height << endl;
cout << "Person's birthday in mm/dd/yyyy format is: "
<< pers.bDay.month << "/" << pers.bDay.day
<< "/" << pers.bDay.year << endl;
}
</pre>
 
Reparem que a estrutura Date tem de ser declarada antes da estrutura Person, pois caso contrário o compilador não entendia a tipologia declarada na estrutura Person.